Go by Example

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 a time value at regular intervals. It keeps sending ticks until stopped.

Receive three ticks, then stop the ticker. defer schedules the stop call to run when the current function returns, including if it 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 repeated work is no longer needed. If your code is too slow to receive every tick, Go may skip ticks instead of storing an unlimited queue. A ticker is not a record of every interval that passed.

Enjoyed this? Get more software craft delivered to your inbox.