1

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()
The One
  • 13
  • 4

1 Answers1

0

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.');
});
sumanta
  • 359
  • 3
  • 7
  • The problem is that the first scheduled job that gets executed is the - console.log('second job') and then immediately after it - console.log('first job'); Which should be the other way around. And also the second job was supposed to execute only 2 minutes after the first job execution. – The One Jan 08 '22 at 05:43
  • please check the time. try to parse it in javascript. – sumanta Jan 08 '22 at 05:50
  • I'm not sure what you meant about parsing in javascript, but from what I found in the Google I now did this - const text = '{"job1":"2022-1-8-17:54"}'; const obj = JSON.parse(text); obj.job1 = new Date(obj.job1); const text1 = '{"job2":"2022-1-8-17:55"}'; const obj1 = JSON.parse(text1); obj1.job2 = new Date(obj.job2); But now only the job1 executes and then the script immediately stops and does not go to the job2. – The One Jan 08 '22 at 15:54