Timer and ticker timer tasks in the Go language

Source: Internet
Author: User

Https://mmcgrana.github.io/2012/09/go-by-example-timers-and-tickers.html

--------------------------------------------------------------------------------------------------------------- -----------

Timers and Tickers

September 28 2012

If you ' re interested on go, be sure to check out Go by Example.

We often want to execute Go code at some point in the future, or repeatedly at some interval. Go ' s built-in timer and ticker features make both of these tasks easy. Let's look at the some examples to see how the They work.

Timers

Timers represent a single event on the future. You tell the timer how long you want to wait, and it gives you a channel that'll be notified at that time. For example, to wait 2 seconds:

 package mainimport  " Time "func main () {timer := time. Newtimer (time. Second * 2) <-timer c println ( "Timer Expired" ) Span class= "P" >               

The <- timer.C blocks on the timer's channel C until it sends a value indicating that the timer expired. You can test the putting of the code in and timers1.go running it with time and go run :

$ time go run timers1.goTimer expiredreal  0m2.113s

If you just wanted to wait, you could has used time.Sleep . One reason a timer may be useful is so you can cancel the timer before it expires. For example, try running this in timers2.go :

PackageMainImport"Time"FuncMain(){timer := time. Newtimer (time. Second) go func () { <-timer. C println ( "Timer Expired" ) } () Span class= "NX" >stop := timer. Stop () println ( "Timer cancelled:"  , stop) }          
$ go run timers2.goTimer cancelled: true

In this case we canceled the timer before it had a chance to expire ( Stop() would return false if we tried to cancel it aft ER it expired.)

Tickers

Timers is for-when-you-want-do something once in the future-tickers is for-when-you-want-do something repeatedly At regular intervals. Here ' s a basic example:

PackageMainImport"Time"Import"FMT"FuncMain(){Ticker:=Time.Newticker(Time.Millisecond*500)GoFunc(){ForT:= range ticker. C {fmt. Println ( "Tick at" t) } } () time. Sleep (time. Millisecond * 1500) ticker.< Span class= "NX" >stop () fmt. Println ( "Ticker stopped" ) }      

Try it out in tickers.go :

$ go run tickers.goTick at 2012-09-22 15:58:40.912926 -0400 EDTTick at 2012-09-22 15:58:41.413892 -0400 EDTTick at 2012-09-22 15:58:41.913888 -0400 EDTTicker stopped

Tickers can stopped just like timers using Stop() the method, as shown at the bottom of the example.

Power of Channels

A great feature of Go ' s timers and tickers are that they hooks into Go ' built-in concurrency mechanism:channels. This allows timers and tickers to interact seamlessly with other concurrent goroutines. For example:

PackageMainImport"Time"Import"FMT"FuncMain(){Timechan:=Time.Newtimer(Time.Second).CTickchan:=Time.Newticker(Time.Millisecond*400).CDonechan:=Make(Chanbool)GoFunc(){Time.Sleep(Time.Second*2)Donechan<-True}()For{select {case <-timeChan: fmt. Println ( "Timer Expired" ) case  <-tickchan: fmt. Println ( "Ticker ticked" ) case donechan: fmt. Println ( "done" ) return } }}             /span>                

Try it out by running the This Code form channels.go :

$ go run channels.goTicker tickedTicker tickedTimer expiredTicker tickedTicker tickedTicker tickedDone

In the "we see" the timer, ticker, and our own custom goroutine all participating in the same select block. The combination of the Go runtime, its channel feature, and timers/tickers use of channels make this kind of cooperation V Ery Natural in Go.

You can learn more on timers, tickers, and other time-related go features in the Go Package time docs.

Timer and ticker timer tasks in the Go language

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.