英文:
Golang difference between timer expired VS stopped?
问题
根据这个例子(https://gobyexample.com/timers),计时器可以被停止或者过期。但是它们有什么区别呢?
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")
}
}
根据代码,timer1会在2秒后过期,而timer2会在1秒后过期。当timer1过期时,会打印出"Timer 1 expired"。而对于timer2,我们使用了一个匿名函数来监听它的过期事件,当timer2过期时,会打印出"Timer 2 expired"。在匿名函数中,我们还调用了timer2的Stop()方法来停止计时器,如果Stop()方法返回true,则表示计时器已经被停止,会打印出"Timer 2 stopped"。
英文:
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")
}
}
答案1
得分: 1
使用指定的持续时间d
(在创建时指定)创建的定时器将在该持续时间过去后到期。这意味着在具有持续时间d
的定时器的通道上等待将仅在持续时间过去后(甚至更晚,取决于调度)解除阻塞调用者。定时器到期可以看作是事件触发。
如果在定时器创建后,您希望阻止其到期(例如,因为您不再对等待感兴趣),您可以停止定时器。这在使用AfterFunc()创建定时器以取消预定的函数执行时更有用。
英文:
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.
答案2
得分: 0
过期意味着计时器已经过去并将时间发送到通道上。Stop()表示程序不再希望计时器触发-如果成功停止,则返回true,如果计时器已经触发并将时间发送到通道上,则返回false。
有关更多详细信息,请参阅https://golang.org/pkg/time/#Timer.Stop。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论