Timers
Timers are for when you want to do something once in the future. Here's an example of a timer that fires after a specified duration.
Key Points
- Timers are used to execute code at a future time.
time.NewTimer()creates a new Timer that provides a channelC.- The
Cchannel sends the time when the timer fires. - Timers can be stopped before they fire by calling the
Stop()method. Stop()returnstrueif the timer was stopped before it fired,falseotherwise.
Timer Example
This example shows how to create and stop a timer.
package main
import (
"fmt"
"time"
)
func main() {
timer1 := time.NewTimer(2 * time.Second)
<-timer1.C
fmt.Println("Timer 1 fired")
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 fired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
time.Sleep(2 * time.Second)
}Timer 2 stopped
Timer 1 firedTimer Operations
| Operation | Syntax | Description |
|---|---|---|
| Create | timer := time.NewTimer(duration) | Creates a new timer. |
| Wait | <-timer.C | Blocks until the timer fires. |
| Stop | timer.Stop() | Stops the timer from firing. |