英文:
Trigger timer prematurely
问题
我有一个循环,它会休眠一段时间。然而,在我的代码的其他地方,我可能需要提前结束这段休眠时间,以便尽快执行后续的逻辑。
for {
timer := time.NewTimer(30 * time.Second)
<-timer.C
// 做一些事情
}
在其他地方...
// 触发定时器
// timer.Trigger() ??
当然,timer.Stop()
会停止定时器,但它会导致程序挂起,不会执行// 做一些事情
。目前,我正在将定时器重置为非常短的持续时间,以便定时器几乎立即过期。
timer.Reset(time.Millisecond)
有没有更好的方法来实现这个需求?
英文:
I have a loop that is sleeping for some period of time. However, elsewhere in my code I might need to end that sleep time prematurely so that the succeeding logic can be executed sooner.
for {
timer = time.NewTimer(30 * time.Second)
<-timer.C
// Do something
}
Elsewhere…
// Trigger timer
// timer.Trigger() ??
Naturally, timer.Stop()
will stop the timer, but it will then cause the program to hang and not drop down to // Do something
. Currently, I am resetting the timer to a very small duration so that the timer will expire basically immediately.
timer.Reset(time.Millisecond)
Is there a better way to do this?
答案1
得分: 2
你可以使用一个取消通道:
cancel := make(chan struct{})
for {
timer := time.NewTimer(30 * time.Second)
select {
case <-timer.C:
doSomething()
case <-cancel:
doSomething()
}
}
当你想忽略计时器并立即执行时,只需在 cancel
通道上发送一条消息:
cancel <- struct{}{}
英文:
You can use a cancellation channel:
cancel := make(chan struct{})
for {
timer = time.NewTimer(30 * time.Second)
select {
case <- timer.C:
doSomething()
case <- cancel:
doSomething()
}
}
When you want to ignore the timer and execute immediately, just send a message on the cancel
channel:
cancel <- struct{}{}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论