I am implementing a node.js not real-time poll creating and voting system, where the admin can create a poll and set a closing date and then when this date is arrived the system closes the poll, send subscribed users an email and the users can't vote anymore. I have implemented every other feature, but I am struggling with closing the polls on that date. I thought about some persistent cron-like scheduler, where I set the job of closing the poll on the established date, but I don't know if this is the best approach. Do you have any ideas on how to solve this problem? Thanks
There are two basic approaches - in-process and out-of-process. In-process is simpler, but it requires your main program to be running. Out-of-process is more robust, because you can use systems whose primary function is to reliably execute scheduled jobs (cron for example).
For the in-process approach in Javascript, I would suggest on startup, go read the poll records that show polls still open (a boolean flag, not a date), subtract the current date from the closing date, and use setTimeout
to schedule a function call that far into the future (or immediately if the difference is negative). That function can do whatever you need (send emails, update records, etc.) The last thing it should do is update the original record to indicate "successfully closed". You want this function to be re-entrant so if your process dies halfway through, the next time it starts it will still see that record of a poll with a closing date in the past, but no "successfully closed" flag, and try again.