Cron Job with NodeJS

Pankaj Kumar - Jun 27 '23 - - Dev Community

Hi All, Suppose we want to execute a task in nodejs on everyday morning at 10AM. Cron job helps us to perform the above task in very easy way.


let app = require('express')(),
server = require('http').Server(app),
bodyParser = require('body-parser'),
express = require('express'),
CronJob = require('cron').CronJob;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(function(err, req, res, next) {
return res.send({ "errorCode": 403, "errorMessage": "Something went wrong!" });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
res.send({ "errorCode": 404, "errorMessage": 'Page not found!' })
});

/*first API to check if server is running*/
app.get('/', function(req, res) {
res.send('hello, jsonworld!');
});

new CronJob('1 * * * * *', function() {
console.log("staring cron");
}, null, true, 'America/Los_Angeles');

server.listen('3000',function(){
console.log('Server running on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

In the above working code, The task will perform in every minute. We have just performed basic stuff to create a basic app in nodejs. For cron job working we have included cron module and then created new object to perform the actual task.

Now lets understand how to set time interval as per requirement.

The placing of each asterisk represents a time value. No try to understand how they represent.

Seconds : 0-59

minutes : 0-59

Hours : 0-23

Days of Month : 1-31

Months : 0-11

Day of week : 0-6

Cron syntax:

new CronJob(‘00 00 07 * * 1–5’, func...

Example:



'* * * * * *' - runs every second
'*/5 * * * * *' - runs every 5 seconds
'10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute
'0 * * * * *' - runs every minute
'0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds)


Enter fullscreen mode Exit fullscreen mode

The above code will repeat our task at 00 seconds, 00 minutes, at hour 7, on every day of the month, from days 1(Monday) through 5(Friday). So i will not repreat on Saturdays and Sundays.

Hope this was helpful to you! Thanks alot.

This article is originally posted over jsonworld

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .