Go by Example

Timers

Schedule a one-shot event with time.NewTimer and cancel it early with Stop.

A time.Timer sends one time value after a chosen delay. A goroutine, a function running while its caller continues, can wait for that value on the timer's channel. Stop cancels a timer that is no longer needed.

Wait for a one-shot timer with select. defer schedules Stop to run when this function returns, so the timer is stopped if it returns early.

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. Reuse a timer when the same code needs to schedule the event again.

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