I want to implement a setup in my node app where the server can send emails to a number of people 24hrs before a specific date. This date is coming from DB.
For example: The date is 25th December, so I need my server to send mails to a group of clients on 24th December. How do I code it today such that it will send the mail in future?
(My node app is hosted on a VPS so it will be running always.)
You can use the node-schedule modules. https://www.npmjs.com/package/node-schedule
var schedule = require('node-schedule');
var date = new Date(2020, 12, 24, 5, 30, 0);
var j = schedule.scheduleJob(date, function(y){ });
Or you can do it the old fashioned way. Something like.
const then = "2020-12-24 05:00:00";
const inter = setInterval(() => {
const now = new Date();
if (Date.parse(now) > Date.parse(then)) {
clearInterval(inter);
}
}, 1000 * 60 * 60 );
Edit:
You could have something like.
const schedules = {};
function dbUpdate() {
const somedate = new Date();
const userid = getUpdatedUser();
cancelSchedule(userid);
createSchedule(userid, somedate);
}
function createSchedule(userid, somedate) {
const date = new Date(somedate);
schedules[userid] = schedule.scheduleJob(date, function(y){ });
}
function cancelSchedule(userid) {
schedules[userid].cancel();
}
Not tested but something along these line