Go Timer and staccato device

Source: Internet
Author: User

1. Timer

The timer in the go language can implement a specific event at a specified point in time, and the essence of the timer is a one-way channel. The timer struct type has a time.time type of one-way Chan, specifically stated as follows:

Type Timer struct {C <-chan time R Runtimetimer}

Initialization can only be done in two ways: time. Newtimer () and time. Afterfunc (), see the following code:

package mainimport  (     "FMT"       "Time") Func main ()  {    // newtimer method accepts a period d means that from now on, after the D time period, The timer expires, the return value is *timer type, and the time expires after it is written to *timer C (chan time. Time) field in     t := time. Newtimer (2 * time. Second)     now := time. Now ()     fmt. Printf ("now time: %v\n",  now)     //  Row code will block the current goroutine until T. An element     expire := <-t.c    fmt is passed in C. Printf ("expire time: %v\n",  expire)} 
Package Mainimport ("FMT" "Time") Func main () {var t *time. Timer F: = func () {fmt. Printf ("Expriation Time:%v\n", time. Now ()) FMT. Printf ("C ' s length:%v\n", Len (T.C))}//The function to execute a custom no accept parameter and output parameter when the timer expires T = time. Afterfunc (1*time. Second, F)//In order to output full time for the result. Sleep (2 * time. Second)}

If you do not use the timer's stop () and reset () method, you can directly use the Quick method of the timers, as follows:

Package Mainimport ("FMT" "Time") Func main () {FMT. Printf ("Now time:%v\n", time. Now ()) c: = <-time. After (5 * time. Second) fmt. Printf ("TimeOut. Now:%v\n ", c)}

If you use Stop () before the timer expires, then no more elements are written to the channel, then the Goroutine that waits for the channel element to be accepted will be blocked, and the only way to recover the stopped timer is to reset it using the Reset () method, the timer can be reused, In particular, multiplexing in the for loop can reduce the resource usage of the program, and the Reset () method is required to reset the timer.


2. Staccato Device

Go provides a multi-loop tool to perform a task, and the breaker is essentially a one-way channel, time. There is a time.time type of one-way Chan in the struct type, specifically stated as follows:

Type Ticker struct {C <-chan time R Runtimetimer}

The breaker is initialized with Newticker () and the code is as follows:

package mainimport  (     "FMT"      "Time") Func main ()  {    ticks := time. Newticker (30 * time. Second)     tick := ticks. C    go func ()  {        // for ... Range ... Equivalent to taking an element from a channel         for _ = range tick {             fmt. Printf ("%vexecute the task.\n",  time. Now ())             //  perform the accept operation again, because there is no value in the channel temporarily, will be blocked until the next trigger expires             _, ok :=  <-tick            if !ok {                 break            }         }    } ()     fmt. Printf ("now: %v.\n",  time. Now ())     time. Sleep (5 * time. Minute)     fmt. Println ("Done.")}

If you do not use the Stop () method of the breaker, you can directly use the Quick method of the breaker, as follows

TICK: = <-time. Tick (5 * time. Second)

This article from "Brave forward, resolutely left" blog, please be sure to keep this source http://quenlang.blog.51cto.com/4813803/1735366

Go Timer and staccato device

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.