mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-19 03:50:11 +08:00
Create 14.5.md
This commit is contained in:
51
eBook/14.5.md
Normal file
51
eBook/14.5.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# 14.5 通道,超时和计时器
|
||||
|
||||
`time`包中有一些有趣的功能可以和通道组合使用。
|
||||
|
||||
其中就包含了`time.Ticker`结构体,这个对象以指定的时间间隔重复的向通道C发送时间值:
|
||||
```go
|
||||
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`语句:
|
||||
```go
|
||||
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](15.9.md))):
|
||||
|
||||
```go
|
||||
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, ...)
|
||||
}
|
||||
```
|
||||
|
||||
## 链接
|
||||
|
||||
- [目录](directory.md)
|
||||
- 上一节:[使用select切换协程](14.4.md)
|
||||
- 下一节:[对协程使用recover](14.6.md)
|
Reference in New Issue
Block a user