Reputation: 2292
A user enters the date and time for a reminder. How can Node know when to send it?
Is the solution having a recursive function with a given setTimeout
interval?
Ex. The reminders are added to a table, with a column isSent, and the interval checks for it i.e. sends the unsent ones?
function checkScheduledNotifications(){
console.log("checking...")
setTimeout(() => {
checkScheduledNotifications();
}, 1000);
}
checkScheduledNotifications();
Upvotes: 1
Views: 1816
Reputation: 708016
There are a number of ways to do this. Since you have them stored in a database already, what I would suggest is that you use a setTimeout()
for the next timer due to fire. Then, each time a notification fires, you query the database for the next timer due to fire and set a new setTimeout()
for that one.
Then, anytime you add a notification from the database, you just need to check if the one you're adding is before the current timer. If so, stop that timer and create a new setTimeout()
for the new one. If no, then just add the new one to the database and it will get its turn in due time.
Then, anytime you remove a notification from the database, check to see if is the one that you currently have a timer for. If not, just remove it from the database. If so, then stop the current timer, remove it from the database and query the database for the next timer and set a timer for it.
This way, the next timer in your database always has a setTimeout()
going for it and you only have one actual system timer in use at any given time so it's using resources efficiently. When your server restarts, you just query the database to find the first notification and set the timer for it. You can probably implement all this with two or three functions.
Upvotes: 4