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"))
}
}
Otput from above snippet is:
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
Why has this happend with no timestamp 16:22:26, 16:22:29 when I delay the ticker?
This is the Ticker source (pardon the line numbers, I copied this off the documentation source page):
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
}
Note the comment
// 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.
What's happening:
Edit: In addition, the documention for NewTicker
(which Tick
is a convenience function for) says:
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.
Though it doesn't explicitly mention it's a channel with a buffer of one.