Tickers
Fire repeatedly at a fixed interval with time.NewTicker, and stop it when its recurring work is no longer needed.
A time.Ticker sends recurring time values at a fixed interval. It keeps sending ticks until stopped; unused tickers can be garbage collected in Go 1.23 and later.
Receive three ticks, then stop the ticker. The deferred call also stops it if the function returns early.
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for i := 0; i < 3; i++ {
fmt.Println(<-ticker.C)
}
}In production
Stop a ticker when its periodic work is no longer needed. If the consumer is slower than the interval, the ticker does not build an unbounded queue; it may drop ticks. Do not treat ticks as a durable count of elapsed intervals.
Enjoyed this? Get more software craft delivered to your inbox.