(1)使用方法
timer := time.NewTicker(time.Duration(GAP) * time.Second)
for {
select {
case now := <-timer.C:
fmt.Println(now)
}
}
(2)NewTicker 函数
func NewTicker(d Duration) *Ticker {
if d <= 0 {
panic(errors.New("non-positive interval for NewTicker"))
}
// Give the channel a 1-element time buffer.
// If the client falls behind while reading, we drop ticks
// on the floor until the client catches up.
c := make(chan Time, 1)
t := &Ticker{
C: c,
r: runtimeTimer{
when: when(d), //下一次要触发的纳秒级时间,绝对时间(当前纳秒级时间+d)
period: int64(d), //每次时间间隔,即d
f: sendTime, //写channel 函数
arg: c, //这里把c作为参数,有个细节的原因是Ticker.C 是receive-only type chan
},
}
startTimer(&t.r)
return t
}
type Ticker struct {
C <-chan Time //定时满足后,执行runtimeTimer 中 f 函数 写channel
r runtimeTimer
}
type runtimeTimer struct {
tb uintptr
i int
when int64
period int64
f func(interface{}, uintptr) // NOTE: must not be closure
arg interface{}
seq uintptr
}
func sendTime(c interface{}, seq uintptr) {
select {
case c.(chan Time) <- Now():
default:
}
}
有空继续
有疑问加站长微信联系(非本文作者)