Go by Example: Timers and Tickers
Go 1.23
Handle time-based events with Timers and Tickers. This example covers `time.NewTimer` for one-off delays and `time.NewTicker` for recurring tasks, demonstrating how to integrate them with channels and select statements.
Code
package main
import (
"fmt"
"time"
)
func main() {
// --- Timers ---
// Timers represent a single event in the future.
timer1 := time.NewTimer(2 * time.Second)
// The timer provides a channel C that receives a value when the time expires
fmt.Println("Timer 1 started")
<-timer1.C
fmt.Println("Timer 1 fired")
// Timers can be stopped before they fire
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 fired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
// --- Tickers ---
// Tickers are for when you want to do something repeatedly at regular intervals.
ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
fmt.Println("Tick at", t)
}
}
}()
// Let the ticker run for a bit
time.Sleep(1600 * time.Millisecond)
ticker.Stop()
done <- true
fmt.Println("Ticker stopped")
}Explanation
Go's time package provides Timers and Tickers for managing time-based events. Timers are for one-off events (fire once after a duration), while Tickers are for recurring events (fire repeatedly at an interval).
Both mechanisms use channels to deliver events. This allows them to be easily integrated with select statements and other channel-based synchronization patterns.
Key operations:
- time.NewTimer(d): Creates a timer that fires after duration d
- timer.Stop(): Cancels the timer (returns true if stopped before firing)
- time.NewTicker(d): Creates a ticker that fires every duration d
- ticker.Stop(): Stops the ticker (does not close the channel)
Code Breakdown
11
Creating a new timer. It will send the current time on its channel C after 2 seconds.
25
Stopping a timer prevents it from firing. This is useful for implementing timeouts or cancelling delayed operations.
32
Creating a ticker that fires every 500ms. Unlike timers, tickers will keep sending values until explicitly stopped.
37-41
Using select to handle the ticker. This allows us to listen for ticks while also listening for a "done" signal to exit the loop cleanly.

