golang 自动收报机是如何工作的?

How does golang ticker work?

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"))                                                                                  
    }                                                                                                                                                 
}          

上面片段的输出是:

开始时间 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
        }

注意评论

// 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.

发生了什么:

  1. 您创建计时器
  2. 计时器产生它的第一个滴答声并对其进行缓冲。
  3. 现在它会等待、唤醒并阻塞,等待您消费以便它可以产生 tick 2。
  4. 最终,您的 goroutine 醒来并立即消耗它产生的前两个滴答声,然后它再次开始产生滴答声。

编辑:此外,NewTicker 的文档(Tick 是一个方便的函数)说:

NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument. It adjusts the intervals or drops ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.

虽然它没有明确提到它是一个缓冲区为 1 的频道。