Files
the-way-to-go_ZH_CN/eBook/14.5.md
2015-12-30 23:01:37 +08:00

1.7 KiB
Raw Blame History

14.5 通道,超时和计时器

time包中有一些有趣的功能可以和通道组合使用。

其中就包含了time.Ticker结构体这个对象以指定的时间间隔重复的向通道C发送时间值

type Ticker struct {
    C <-chan Time // the channel on which the ticks are delivered.
    // contains filtered or unexported fields
    ...
}

时间间隔的单位是ns纳秒int64在工厂函数time.NewTicker中以Duration类型的参数传入:func Newticker(dur) *Ticker

在协程周期性的执行一些事情(打印状态日志,输出,计算等等)的时候非常有用。

调用Stop()使计时器停止,在defer语句中使用。这些都很好的适应select语句:

ticker := time.NewTicker(updateInterval)
defer ticker.Stop()
...
select {
case u:= <-ch1:
    ...
case v:= <-ch2:
    ...
case <-ticker.C:
    logState(status) // call some logging function logState
default: // no value ready to be received
    ...
}

time.Tick()函数声明为Tick(d Duration) <-chan Time当你想返回一个通道而不必关闭它的时候这个函数非常有用它以d为周期给返回的通道发送时间d是纳秒数。如果需要像下边的代码一样限制处理频率函数client.Call()是一个RPC调用这里暂不赘述参见章节15.9

import "time"

rate_per_sec := 10
var dur Duration = 1e9 / rate_per_sec
chRate := time.Tick(dur) // a tick every 1/10th of a second
for req := range requests {
  <- chRate // rate limit our Service.Method RPC calls
  go client.Call("Service.Method", req, ...)
}

链接