提前触发计时器

huangapple go评论72阅读模式
英文:

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)
    &lt;-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 &lt;- timer.C:
        doSomething()
    case &lt;- cancel:
        doSomething()
    }
}

When you want to ignore the timer and execute immediately, just send a message on the cancel channel:

cancel &lt;- struct{}{}

huangapple
  • 本文由 发表于 2017年6月1日 00:08:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/44289704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定