zoukankan      html  css  js  c++  java
  • go语言中的timer 和ticker定时任务

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

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

    Timers and Tickers

    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.

  • 相关阅读:
    启动hadoop集群的时候只能启动一个namenode,另一个报错There appears to be a gap in the edit log. We expected txid 6, but got txid 10.
    YARN的HA
    CSS3 文本效果:text-shadow、box-shadow、text-overflow、word-wrap、word-break
    CSS3 渐变(Gradients):在两个或多个指定的颜色之间显示平稳的过渡
    CSS3 背景:几个新的背景属性,提供更大背景元素控制
    CSS3 圆角:使用 CSS3 border-radius 属性,你可以给任何元素制作 "圆角"
    CSS3 边框:创建圆角边框,添加阴影框
    CSS 网页布局的集中实现方式
    CSS 计数器:通过一个变量来设置,根据规则递增变量
    CSS 表单:使用 CSS 来渲染 HTML 的表单元素
  • 原文地址:https://www.cnblogs.com/oxspirt/p/7088938.html
Copyright © 2011-2022 走看看