mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-19 03:50:11 +08:00
1.7 KiB
1.7 KiB
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, ...)
}
链接
- 目录
- 上一节:使用select切换协程
- 下一节:对协程使用recover