Timers
Schedule a one-shot event with time.NewTimer and cancel it early with Stop.
A time.Timer sends one value after a duration. Its channel lets a goroutine wait for the event, and Stop cancels a timer that is no longer needed.
Wait for a one-shot timer with a select. Deferring Stop also cancels it if this function returns before it fires.
package main
import (
"fmt"
"time"
)
func main() {
timer := time.NewTimer(100 * time.Millisecond)
defer timer.Stop()
select {
case <-timer.C:
fmt.Println("timer fired")
}
}In production
Call Stop when the event should be cancelled, not to make the timer eligible for garbage collection. Since Go 1.23, the runtime can collect unreferenced timers that have not fired. Reuse or stop timers when that better matches the event lifecycle.
Enjoyed this? Get more software craft delivered to your inbox.