Reputation: 3347
Based on this example (https://gobyexample.com/timers), the timer can be either stopped or expired. But what are the differences?
package main
import "time"
import "fmt"
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")
}
}
Upvotes: 0
Views: 2658
Reputation: 2606
A Timer created with a certain duration d
(specified at creation time) expires when such duration has passed. This means that waiting on the channel of a Timer with duration d
will unblock the caller only after the duration has elapsed (maybe even later, depending on scheduling). Timer expiration can be thought of as event firing.
If, after Timer creation, you want to prevent its expiration (e.g. because you're not interested in waiting anymore), you can Stop() the Timer. This is more useful when the Timer has been created with AfterFunc(), in order to cancel the scheduled function execution.
Upvotes: 1
Reputation: 572
Expired means that the timer has elapsed and sent the time on the channel. Stop() means that the program no longer wants the time to fire - it returns true if it was stopped successfully and false if the timer has already fired and sent the time on the channel.
See https://golang.org/pkg/time/#Timer.Stop for more details.
Upvotes: 0