英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论