Scheduling in Node.js with node-cron
It’s easy to get up and running with scheduled events in your Node.js app with node-cron, a library which brings the power of cron to Node.
Here I’ll show you a simple flow which has worked well for me in production. As an example I’ll use an express.js setup, where server.js is where the app is launched:
// server.js
import express from 'express';
import syncUsers from 'events/syncUsers';
import weeklyMail from 'events/weeklyMail';
const app = express();
function start() {
app.get('/', (res) => res.send('Hello World'));
syncUsers();
weeklyMail();
app.listen(3000);
}
start();
So we are calling the scripts in server.js, but the actual schedule cron-based code lives inside the script. Let’s have a look at that:
// events/weeklyMail.js
import cron from 'node-cron';
import cronJobTimeIntervals from 'config/cronJobTimeIntervals';
export default function weeklyMailtimeInterval(timeInterval = cronJobTimeIntervals.everyWednesdayAtNoon) {
// perform on start?
// doMail();
cron.schedule(timeInterval, doMail);
}
function doMail() {
console.log('Sending weekly mail')
// do mail stuff
}
So we import cron from "node-cron"
and use the method cron.schedule()
, which takes two arguments - the schedule (a cron syntax string) plus a function (the code you want to execute).
At the top of the file in a default export function I call cron.schedule
with the schedule in an argument I named timeInterval
and also my doMail()
function where my script actually runs.
I also gave my timeInterval
a default value of everyWednesdayAtNoon
… which just a human readable alias for the real cron syntax. I store these aliases in a simple config file which looks like this.
// config/cronJobTimeIntervals.js
const timeInterval = {
every15Mins: '*/15 * * * *',
everyHour: '0 * * * *',
every4Hours: '0 */4 * * *',
everyDay: '0 0 * * *',
everyWeekdayAtNoon: '0 12 * * 1-5',
everyWednesdayAtNoon: '0 12 * * wed',
};
export default timeInterval;
As we’re calling the exported function in server.js, you could choose to also run your cron job every time the server starts (i.e. on a new deployment), which is useful if you had to do something like sync your database with an external API. I’ve shown this on line 6 above.
Here’s what my schedule config file looks like:
(I like to use crontab.guru to generate valid cron syntax).
So as long as your server is up and running (with something like pm2) your jobs will run on time every time, thanks to the power of cron.