time包里有个Timer计时器的功能,主要的结构和函数有:
三个基本用法:
Afterreturn NewTimer(d).CNewTimerTimerResetStopNewTimer
AfterFuncd DurationfTimerTimer.CResetStop
NewTimerAfterFunc
NewTimer:
NewTimersendTimeTimer.C
AfterFunc:
AfterFuncgoFuncgoFuncfTimer.C
NewTimerTimer
Timer
ResetStop
TimerStopTimer.C
会导致程序阻塞,无法退出。
TimerResetStop
ResetStoptimeReset
For a Timer created with NewTimer, Reset should be invoked only on stopped or expired timers with drained channels.
对于使用NewTimer创建的Timer,Reset应该用在已经停止或过期,并已经排空管道的计时器上。
If a program has already received a value from t.C, the timer is known to have expired and the channel drained, so t.Reset can be used directly. If a program has not yet received a value from t.C, however, the timer must be stopped and—if Stop reports that the timer expired before being stopped—the channel explicitly drained:
如果一个程序已经从t.C中接收了值,计时器过期了并且管道已被排空,Reset可以直接使用。但如果程序还未从t.C中接收值,而计时器需要被停止,并且Stop方法报告计时器在被停止前已经过期,则管道需要被显式的排空:
This should not be done concurrent to other receives from the Timer's channel.
这个操作不应与其他程序接收计时器的管道同时发生。
注意,上面的内容其实还没表述完全。
Stopfalset.C
- Stop前已经被Stop,t.C为空
- Stop前已经过期,计时器向t.C中写入内容,t.C为满
- Stop前已经过期,计时器向t.C中写入内容,t.C的信息已被其他程序接收,t.C为空
前面文档中的程序,仅在第2种情况会按照预期运行。
<-t.C
timerStop
timerStop
- select走default分支,跳过阻塞,但应考虑到计时器并不是当前Stop停止的
- select进行显式排空,但应考虑到计时器并未被成功停止,并且t.C的内容被抛弃了
- select走default分支,跳过阻塞,但应考虑到计时器并未被成功停止,并且t.C的内容被其他程序利用了
timerStop
否则,应该充分考虑自己程序的需求,进行必要的修改。