Use timers and tickers with version rules
Use timers and tickers with version rules
A timer signals once after a duration; a ticker signals repeatedly at a positive interval. NewTimer and NewTicker expose a channel C: receiving with <- waits for a signal. A channel is a communication mechanism covered in the next chapter; no goroutines are needed in these examples. Save each example as main.go and run go run main.go. Outputs report events, not exact timings.
package main
import ( "fmt" "time")
func main() { t := time.NewTimer(5 * time.Millisecond) defer t.Stop() <-t.C fmt.Println("timer fired")}The receive waits for the timer signal. Stop cancels a pending timer; it does not close its channel. When testing on Go 1.23, channel semantics depend on the main module’s go directive: go 1.23 or later opts into the new synchronous timer channels, with stronger Stop and Reset guarantees and collection of unreferenced timers/tickers. In Go 1.23, GODEBUG=asynctimerchan=1 forces legacy mode and =0 forces new mode. See https://go.dev/wiki/Go123Timer. Older buffered timers need coordinated stop/drain before reuse; do not copy a reset recipe across modes. AfterFunc uses a callback and has separate concurrency rules.
Expected output:
timer firedBound a repeating task
package main
import ( "fmt" "time")
func main() { ticker := time.NewTicker(5 * time.Millisecond) defer ticker.Stop() for i := 1; i <= 3; i++ { <-ticker.C fmt.Println("tick", i) }}The loop receives three signals and then exits; defer stops the ticker. A slow receiver may miss ticks because the ticker adjusts or drops them; do not treat signal count as exact elapsed time. Stop does not close C, so ranging over C will not automatically end after Stop. NewTicker panics for a nonpositive interval. These short examples are bounded by the harness timeout; real services need cancellation and explicit lifetime ownership. For new-mode Reset demonstrations use a go.mod with go 1.23 and verify the runtime configuration.
Expected output:
tick 1tick 2tick 3Try it locally
Create a ticker at 5 milliseconds, receive exactly two signals, print ready for each, and stop the ticker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Time and scheduling 07: Use timers and tickers with version rules
Check the lesson objective before moving on.
Does Ticker.Stop close C?
On Go 1.23, which main-module directive normally selects the new timer behavior when no override is set?