A Timer represents a single event in the future. You tell the Timer how long you want to wait, and it provides a channel that will be notified at that time.
package main
import (
"fmt"
"time"
)
func main() {
timer1 := time.NewTimer(time.Second * 2)
<-timer1.C
fmt.Println("Timer 1 expired")
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 expired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
}
In this example, a timer is created with a duration of 2 seconds and waits for it to expire using the <-timer1.C
channel. Another timer is created with a duration of 1 second and starts a goroutine that waits for it to expire using the <-timer2.C
channel. The timer2.Stop()
function is called to stop the timer before it expires. If the timer was stopped, the if
statement will print “Timer 2 stopped”.
Timers are used to schedule events in the future. A Timer represents a single event in the future. The timer.After function returns a channel that blocks for a specified duration and then sends the current time. Timers can be stopped before the timer fires. The time.Timer type has a Stop method which returns a bool indicating if the timer was indeed stopped. The following example demonstrates the usage of timers:
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")
}
}
This program will output:
Timer 1 fired
Timer 2 stopped
Leave a Reply