Anijit Sau
Anijit Sau

Reputation: 575

Schedule multiple functions to run at specific interval in Node JS (CRON JOB)

I want to execute three functions at specific time interval using Node JS. I have gone through this article I need a Nodejs scheduler that allows for tasks at different intervals

I have tried with node-cron and node-schedule. But it is not working !!

My code is like below,

var schedule = require('node-schedule')


var fs = require('fs')
var tar = require('tar')

var notification = require('./notification')

let changeInDir = function () {
    console.log('Testing CRON JOB !!!', new Date().toLocaleString())
    fs.watch('./test', (event, filename) => {
        console.log('a', event, 'event occurred.. on file', filename)
    })
}

// schedule a CRON Job
var changeFile = schedule.scheduleJob('4 * * * * *', changeInDir);


// send the Monthly snapshots
var monthlySnapshot = schedule.scheduleJob('5 * * * * *', notification.getViewDetails('Monthly'))

// send the Daily snapshots
var dailySnapshot= schedule.scheduleJob('10 * * * * *', notification.getViewDetails('Daily'))

I want that that monthlySnapshot will run at 5 seconds interval while dailySnapshot will run at 10 seconds interval and changeFile will run at 4 seconds interval.

Now monthlySnapshot and dailySnapshot access MySQL database to get the data and send email accordingly. If I schedule only the changeFile and comments others it works fine. But when I try to execute all the three it gives the following error message and crashed.

C:\Users\asau\Documents\LeaderBoardNodejs\archlb\src\server\node_modules\node-schedule\lib\schedule.js:174
    this.job.execute();
             ^

TypeError: this.job.execute is not a function
    at Job.invoke (C:\Users\asau\Documents\LeaderBoardNodejs\archlb\src\server\node_modules\node-schedule\lib\schedule.js:174:14)
    at Timeout._onTimeout (C:\Users\asau\Documents\LeaderBoardNodejs\archlb\src\server\node_modules\node-schedule\lib\schedule.js:542:11)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)
[nodemon] app crashed - waiting for file changes before starting...

How to solve that? Any example using node-cron or node-schedule is OK.

Database access is working fine when I solely use nodemon notification.js and correctly send emails. No issues in there.

Upvotes: 0

Views: 4282

Answers (1)

Mustafa Mamun
Mustafa Mamun

Reputation: 2651

I use node cron https://www.npmjs.com/package/cron

var momentTz = require('moment-timezone');
var CronJob = require('cron').CronJob;
var job = new CronJob('*/4 * * * * *', function() {
var a = momentTz.tz("Europe/Helsinki");
 //your logic
}, function () {

   console.log('work ended');
},
true,
'Europe/Helsinki'
);

job.start();

it runs every 4 sec

Upvotes: 1

Related Questions