0

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

Edson Bueno
  • 89
  • 1
  • 5
  • Is your NodeJS program always running on the server? – Aditya R Oct 09 '16 at 22:43
  • I am not sure if I truly understood the question, but I will say that yes, it is. – Edson Bueno Oct 09 '16 at 22:46
  • Are you using a database or is everything stored in memory? – Aditya R Oct 09 '16 at 22:48
  • Database, DynamoDB – Edson Bueno Oct 09 '16 at 22:49
  • I'm not an expert in DynamoDB but couldn't you have a field called `expires` for each DB entry (representing one poll) and check whenever a client makes a request that the poll isn't closed? Using that you can tell the client that the poll is over and that the form needs to be disabled. – Aditya R Oct 09 '16 at 22:51
  • Yes, i could, but I need to do other jobs when the date is arrived, like sending the results by e-mail to some subscribed users. I already have a closing_date field, where I store the date when the poll should end. – Edson Bueno Oct 09 '16 at 22:55

1 Answers1

0

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.

Rex M
  • 142,167
  • 33
  • 283
  • 313
  • Thanks for the answer. Any suggestions on reading about making re-entrant functions in Javascript? – Edson Bueno Oct 10 '16 at 11:48
  • @EdsonBueno just read about it in general, there's nothing particular to a specific language about it. – Rex M Oct 10 '16 at 18:22