javascriptnode.jsnode-schedule

How to use node-schedule module in Node.js


I'm new to js and programming in general. I need to have separated scheduled jobs in my script using node-schedule, but I can't figure out how because each time when 1st scheduled job is to be executed it immediately executes both the first and the second job.

And the functions even get executed the other way around, the second function gets executed first (which is set to a later time than first function) and the first function gets executed second.

My code:

const schedule = require('node-schedule');

//first job
let firstPost = new Date('2022-01-08T06:30:00.000+4:00');

schedule.scheduleJob(firstPost, function () {
    console.log('first job');
});

// second job
let secondPost = new Date('2022-01-08T06:32:00.000+4:00');

schedule.scheduleJob(secondPost, function () {
    console.log('second job'); 
});

Update (solution): Thanks to Sumanta's answer, I managed to get it working through parsing string to date. Here is the working code in case anyone stumbles upon the same problem and needs help.

const schedule = require('node-schedule');

const unParsedText1 = '{"job1Time":"2022-1-9-14:25", "job2Time":"2022-1-9-14:26"}';
const parsedText1 = JSON.parse(unParsedText1);
parsedText1.job1Time = new Date(parsedText1.job1Time);
parsedText1.job2Time = new Date(parsedText1.job2Time);

function test1() {
    schedule.scheduleJob(parsedText1.job1Time, function () {
        console.log('First job');
    });
}

function test2() {
    schedule.scheduleJob(parsedText1.job2Time, function () {
        console.log('second job');
    });
}
test1()
test2()

Solution

  • node-schedule take two arguments. 1st one being the time(in cron or equivalent syntax.) 2nd argument being the callback function which will be triggered at the time syntax match.

    check the Date format.

    node> new Date('2022-01-08T06:30:00.000+4:00')
    Invalid Date
    

    Examples with the cron format:

    const schedule = require('node-schedule');
    const date = new Date(2012, 11, 21, 5, 30, 0);
    
    const job = schedule.scheduleJob(date, function(){
      console.log('The world is going to end today.');
    });