Timers
package main
import (
"fmt"
"time"
)
func main() {
// Creating a timer 'timer1' that will fire after 2 seconds
timer1 := time.NewTimer(2 * time.Second)
// Blocking until the timer1's channel 'C' sends a value (indicating the timer has fired)
<-timer1.C
fmt.Println("Timer 1 fired")
// Creating a timer 'timer2' that will fire after 1 second
timer2 := time.NewTimer(time.Second)
// Launching a goroutine to handle the firing of timer2
go func() {
// Blocking until the timer2's channel 'C' sends a value
<-timer2.C
fmt.Println("Timer 2 fired")
}()
// Stopping timer2 before it fires
stop2 := timer2.Stop()
// Checking if timer2 was successfully stopped
if stop2 {
fmt.Println("Timer 2 stopped")
}
// Giving some time for the goroutine to handle the stopping of timer2
time.Sleep(2 * time.Second)
}Output
Last updated