In my app every user will have a particular deliverydate when they buy a subscription so once they buy the subscription we will show an option saying "Remind me after" for reminding few things exactly 24 hours before the delivery date (A button on react frontend which calls remindmeafter API on nodejs)and I want to create a cron job for this use case.
So Far Here are my trials:
- Initially I have tried node-schedule as they are supporting specific date and time based cron job and here is my code for the same.
const date = new Date(moment(subcriptiondata.deliveryDate, 'DD-MM-YYYY').subtract(1, 'days').subtract(5, 'hours').add(30, 'seconds').tz('America/Toronto'))
const job = schedule.scheduleJob(date, function() {
ejs.renderFile(emailUser, {
data: MailObj
}, (err, results) => {
if (err) {
logger.info('ERROR::::while sending reminder' + err);
}
emailApi.sendEmailApi(
`Reminder `,
'Reminder',
results,
subcriptiondata.email,
'Mail sent failure',
'Mail sent successfully',
process.env.EMAIL_SENDER
);
});
})
However I've then found on their documentation that node-schedule doesn't persist the data on server restart and which isn't suitable for my app.
- I have then tried it using cron module and as per their documentation they also support date-based cron job and here is my code for it :
const date = new Date(moment(subcriptiondata.deliveryDate, 'DD-MM-YYYY').subtract(1, 'days').subtract(5, 'hours').add(30, 'seconds').tz('America/Toronto'))
const job = new CronJob(date, function() {
ejs.renderFile(emailUser, {
data: MailObj
}, (err, results) => {
if (err) {
logger.info('ERROR::::while sending reminder' + err);
}
emailApi.sendEmailApi(
`Scheduled Reminder `,
'Scheduled Reminder',
results,
subcriptiondata.email,
'Mail sent failure',
'Mail sent successfully',
process.env.EMAIL_SENDER
);
});
}, null, true, 'America/Toronto');
I have deployed and tried both the codes however none of them are working as I'm not receiving any emails for the scheduled date.It would be great if someone here can help me with this on what I'm doing wrong here and I would prefer the second one i.e, using cron module as it persists server restarts.
Update: I have tried with every 5 mins trigger an email instead of specific date and I did received emails in this case.