Learn How to make scalable cron jobs in Nodejs
What is a Cron Job?
A cron job is basically a Linux command used for scheduling tasks to be executed sometime in the future. This is normally used to schedule a job that is executed periodically — for example, to send out a notice every morning or send a unique discount coupon to customers based on a business logic.
Why Node js ?
It is very simple . Node js is lightweight , fast and works like a charm microservices architecture.
Let us see how simple it is to setup .
Dependencies -
npm i --save node-schedule dotenv
Test Function -
const myCronJob = async () => {
try {
console.info("myCronJob Start")/* perform your async operation *
await asyncOperation(2000)console.info("myCronJob End")}
catch (err) {console.error(`Func.cronJobFunc: ${err}`);}
}
Let us make a mock function which will perform the async operation -
const asyncOperation = (ms)=> new Promise(resolve => setTimeout(resolve, ms));
Cron Expression -
1. A cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule .
<minute> <hour> <day-of-month> <month> <day-of-week> <command>
2. Let us schedule our batch job at a specific time everyday.
import { scheduleJob } from “node-schedule”;
scheduleJob(‘0 8 * * *’, () => myCronJob);
3. Here the cron expression is 0 8 * * * which means every day at 8am.
4. You can also make the cron expression configurable by adding a config variable in the .env file , for this case MY_CRON_EXP=0 8 * * * .
import { scheduleJob } from “node-schedule”;
require(“dotenv”).config();
scheduleJob(process.env.MY_CRON_EXP, () => myCronJob);
Note : Make sure to point to the path where you are calling scheduleJob ,
this way the server always listens to your batch job and executes whenever the cron expression is true.
Start Script -
node server.js
Output -
myCronJob Start
myCronJob End
That’s it ! It was that simple this solution can be used to make robust batch jobs by calling databases, implementing a business logic or sending dynamic emails to clients . Every task can be automated !
Thanks for the read . Feel free to ask any questions☺