Timers and tickers
- Version
- 1.27
- Review
- Draft
Summary#
A timer fires once, and a ticker fires repeatedly. Both deliver on a channel named C. time.AfterFunc instead calls a function in its own goroutine after the delay.
Syntax#
timer := time.NewTimer(delay)
defer timer.Stop()
ticker := time.NewTicker(period)
defer ticker.Stop()
time.AfterFunc(delay, callback)
To reuse a stopped timer, call timer.Reset(delay) before receiving from timer.C.
Example#
package main
import (
"fmt"
"time"
)
func main() {
timer := time.NewTimer(time.Hour)
fmt.Println("stopped pending timer:", timer.Stop())
fmt.Println("was active at reset:", timer.Reset(time.Millisecond))
<-timer.C
fmt.Println("timer fired")
fmt.Println("stopped fired timer:", timer.Stop())
ticker := time.NewTicker(time.Millisecond)
for tick := range 3 {
<-ticker.C
fmt.Println("tick", tick+1)
}
ticker.Stop()
done := make(chan struct{})
time.AfterFunc(time.Millisecond, func() {
fmt.Println("callback ran")
close(done)
})
<-done
}
Expected output#
stopped pending timer: true
was active at reset: false
timer fired
stopped fired timer: false
tick 1
tick 2
tick 3
callback ran
Common mistakes#
Ticker.Stop leaves C open. Use a select with a separate done signal to end a receive loop. A ticker may drop ticks for a slow receiver, so measure elapsed time with a clock. A timer from AfterFunc has a nil C. When completion matters, wait for a started callback separately because Stop can return while it is still running.
Version applicability#
Timer.Reset arrived in Go 1.1. The other APIs shown date back to Go 1.0. The example requires Go 1.22 for integer range.
Go 1.23 introduced unbuffered timer and ticker channels. A receive after Stop or Reset then cannot read a stale value, and the garbage collector can reclaim unreferenced timers and tickers without an explicit stop. In Go 1.23 through 1.26, this was the default for main modules declaring go 1.23 or later. GODEBUG=asynctimerchan=0 forced the new behavior and asynctimerchan=1 forced the old behavior. Go 1.27 always uses unbuffered channels. Remove asynctimerchan=1 from GODEBUG before upgrading because Go 1.27 rejects the old value at startup.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0