• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

go语言中的timer和ticker定时任务

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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

September 28 2012

If you’re interested in 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 some examples to see how they work.

Timers

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

package main

import "time"

func main() {
    timer := time.NewTimer(time.Second * 2)
    <- timer.C
    println("Timer expired")
}

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

$ time go run timers1.go
Timer expired
real  0m2.113s

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

package main

import "time"

func main() {
    timer := time.NewTimer(time.Second)
    go func() {
        <- timer.C
        println("Timer expired")
    }()
    stop := timer.Stop()
    println("Timer cancelled:", stop)
}
$ go run timers2.go
Timer 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 after it expired.)

Tickers

Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s a basic example:

package main

import "time"
import "fmt"

func main() {
    ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
    }()
    time.Sleep(time.Millisecond * 1500)
    ticker.Stop()
    fmt.Println("Ticker stopped")
}

Try it out in tickers.go:

$ go run tickers.go
Tick at 2012-09-22 15:58:40.912926 -0400 EDT
Tick at 2012-09-22 15:58:41.413892 -0400 EDT
Tick at 2012-09-22 15:58:41.913888 -0400 EDT
Ticker stopped

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

Power of Channels

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

package main

import "time"
import "fmt"

func main() {
    timeChan := time.NewTimer(time.Second).C
    
    tickChan := time.NewTicker(time.Millisecond * 400).C
    
    doneChan := make(chan bool)
    go func() {
        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
      }
    }
}

Try it out by running this code form channels.go:

$ go run channels.go
Ticker ticked
Ticker ticked
Timer expired
Ticker ticked
Ticker ticked
Ticker ticked
Done

In this case 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 very natural in Go.

You can learn more about timers, tickers, and other time-related Go features in the Gotime package docs.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
图解Go语言内存分配发布时间:2022-07-10
下一篇:
[日常]Go语言圣经-错误,函数值习题发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap