Go断续器实例

计时器是当想在未来做一些事情 - tickers是用于定期做一些事情。 这里是一个例行程序,周期性执行直到停止。

代码机使用与计时器的机制类似:发送值到通道。 这里我们将使用通道上的一个范围内来迭代值,这此值每500ms到达。

代码可以像计时器一样停止。当代码停止后,它不会在其通道上接收任何更多的值。我们将在1600ms后停止。

当运行这个程序时,ticker应该在我们停止之前打3次。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

timers.go的完整代码如下所示 -

package main

import "time"
import "fmt"

func main() {

    // Tickers use a similar mechanism to timers: a
    // channel that is sent values. Here we'll use the
    // `range` builtin on the channel to iterate over
    // the values as they arrive every 500ms.
    ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
    }()

    // Tickers can be stopped like timers. Once a ticker
    // is stopped it won't receive any more values on its
    // channel. We'll stop ours after 1600ms.
    time.Sleep(time.Millisecond * 1600)
    ticker.Stop()
    fmt.Println("Ticker stopped")
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run tickers.go
Tick at 2017-01-21 14:24:48.8807832 +0800 CST
Tick at 2017-01-21 14:24:49.380263 +0800 CST
Tick at 2017-01-21 14:24:49.882174 +0800 CST
Ticker stopped

上一篇:Go计时器实例

下一篇:Go工作池实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程