提前触发计时器

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

Trigger timer prematurely

问题

我有一个循环,它会休眠一段时间。然而,在我的代码的其他地方,我可能需要提前结束这段休眠时间,以便尽快执行后续的逻辑。

  1. for {
  2. timer := time.NewTimer(30 * time.Second)
  3. <-timer.C
  4. // 做一些事情
  5. }

在其他地方...

  1. // 触发定时器
  2. // timer.Trigger() ??

当然,timer.Stop()会停止定时器,但它会导致程序挂起,不会执行// 做一些事情。目前,我正在将定时器重置为非常短的持续时间,以便定时器几乎立即过期。

  1. 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.

  1. for {
  2. timer = time.NewTimer(30 * time.Second)
  3. &lt;-timer.C
  4. // Do something
  5. }

Elsewhere…

  1. // Trigger timer
  2. // 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.

  1. timer.Reset(time.Millisecond)

Is there a better way to do this?

答案1

得分: 2

你可以使用一个取消通道:

  1. cancel := make(chan struct{})
  2. for {
  3. timer := time.NewTimer(30 * time.Second)
  4. select {
  5. case <-timer.C:
  6. doSomething()
  7. case <-cancel:
  8. doSomething()
  9. }
  10. }

当你想忽略计时器并立即执行时,只需在 cancel 通道上发送一条消息:

  1. cancel <- struct{}{}
英文:

You can use a cancellation channel:

  1. cancel := make(chan struct{})
  2. for {
  3. timer = time.NewTimer(30 * time.Second)
  4. select {
  5. case &lt;- timer.C:
  6. doSomething()
  7. case &lt;- cancel:
  8. doSomething()
  9. }
  10. }

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

  1. 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:

确定