Which is best way to wait event until expire in golang, timer or goroutine loop?

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

Which is best way to wait event until expire in golang, timer or goroutine loop?

问题

在这种情况下,我认为使用goroutine更适合。使用goroutine可以在后台运行一个循环,每隔半小时检查事件是否发生。这种方法不需要创建大量的定时器,而且可以更灵活地控制循环的频率。另外,使用goroutine还可以方便地处理其他任务,而不会阻塞主线程。因此,我建议选择使用goroutine来实现状态机的逻辑。

英文:

the state machine's first state is waiting for one event, if the event doesn't happen in certain days, the status machine will switch to the second state. If the event happened in the period, the state machine will switch to the third state.

I have two option:
1, Use a timer. Set up a timer as certain days. When time is up, checking does the event happened or not. If happened, switch to the third state. If not, switch to the second state. It is possible that thousands of timers will be created in the period.

2, Use a looping with routine. Start a routine to run a loop. Every half hour, the goroutine will check the event happened or not. If the event happened, switch to the third state. Else, keep looping until expired the certain days, then switch to the second state.

My question is time.Timer vs goroutine, which is more suit for this case?

答案1

得分: 2

由于你提到了一个以天为单位的时间段,根据给出的两个选项,你应该选择第二个选项。这样,你可以将状态存储到文件(或数据库)中,并在需要时重新启动进程。第一个选项使得存储状态更加困难,但仍然是可能的。

英文:

Since you mention a time period of days, of the two given, you should probably go with the second option. This way you can store state to a file (or database) and restart the process if necessary. The first option makes storing the state more difficult, but still possible.

huangapple
  • 本文由 发表于 2016年4月12日 15:22:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/36566288.html
匿名

发表评论

匿名网友

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

确定