I am working on an Angular(frontend) and NodeJS(APIs) application. I want to schedule email on particular dates without any external call. I explored node-schedule. But how should I ensure that it runs forever in my NodeJs APIs? Like where should I put the code - in app.js or give it a route?
You are on the right track. You have to use cron service for this. And node-schedule is a good choice for this.
So first, make a file named email-service.js.
Inside that put your logic.
email-service.js
var node = require('node-schedule');
var sendEmail = node.scheduleJob('0 6 * * *', function(){
console.log('Starting..');
init(); // write your logic here to send email
});
function init() {
console.log('Your logic goes here.');
}
module.exports = {
cronService: cronService
}
app.js
In the app.js import email-service.js.
const emailService = require('email-service')
emailService.sendEmail.start(); // start service..
You can schedule a cron accordingly. Below is the format of the cron.
The cron format consists of:
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ │
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
One more thing, if the application is restarts then your schedule event get cancelled. so it might be a good approach if you save your event in a db and marked them complete or incomplete. And re-schedule your incomplete events at the restart of the application.
I use this to make sure all events runs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With