func Tick() {
fmt.Println("startTime", time.Now().Format("2006-01-02 15:04:05"))
t := time.NewTicker(time.Second * 3)
time.Sleep(time.Second * 12)
for {
stamp := <-t.C
fmt.Println("tickTime", stamp.Format("2006-01-02 15:04:05"))
}
}
Run Code Online (Sandbox Code Playgroud)
上面代码段的输出是:
startTime 2016-06-22 16:22:20
tickTime 2016-06-22 16:22:23
tickTime 2016-06-22 16:22:35
tickTime 2016-06-22 16:22:38
tickTime 2016-06-22 16:22:41
tickTime 2016-06-22 16:22:44
为什么这会发生时间戳没有时间戳16:22:26,16:22:29当我延迟这个时间戳?
这是Ticker源代码(请原谅行号,我将其从文档源页面中复制出来):
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),
period: int64(d),
f: sendTime,
arg: c,
},
}
startTimer(&t.r)
return t
}
Run Code Online (Sandbox Code Playgroud)
注意评论
// 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.
Run Code Online (Sandbox Code Playgroud)
发生了什么:
编辑:此外,NewTicker(这Tick是一个便利功能)的文件说:
NewTicker返回一个新的Ticker,其中包含一个通道,该通道将使用duration参数指定的句点发送时间.它调整间隔或下降滴答以弥补慢速接收器.持续时间d必须大于零; 如果没有,NewTicker将会恐慌.停止代码以释放相关资源.
虽然它没有明确提到它是一个缓冲区为1的通道.