Cron jobs with nodejs

sample appliction image

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's see the working code:

let app = require('express')(),
server = require('http').Server(app),
bodyParser = require('body-parser'),
express = require('express'),
CronJob = require('cron').CronJob;
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');
    console.log('Server running on port 3000');


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...


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.


You can download complete code from here. Download Code