Reputation: 71
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?
Upvotes: 2
Views: 4505
Reputation: 175
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.
Upvotes: 4
Reputation: 7156
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)
Upvotes: 5
Reputation: 26
We use PM2 (https://pm2.io/runtime/) - It's a process manager that keeps your process running and has configuration that will allow you to schedule a node job to run according to a cron schedule. There's alot more to it, but if you're looking to improve the operation of your API, this tool is really good - and free.
Upvotes: 0
Reputation: 4928
Sounds like something you can achieve with nodeCron.
You may have a look at the answer here too
You can shcedule your scheduler to execute on a specific time like
var schedule = require('node-schedule');
var j = schedule.scheduleJob('42 * * * *', function(){
console.log('The answer to life, the universe, and everything!');
});
The example above is from node-cron npm page. Please have a look and their github for better understanding.
Upvotes: 1