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

Issue

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?

Solution

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.

Answered By – matt.s

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.