Abhishek Pankar
Abhishek Pankar

Reputation: 743

Stop Cron Job inside the scheduler Node.js

I've created a cron-job to run a task and I want it to stop at some specific condition inside the scheduler, but it is not working.

How can I stop cron job inside the scheduler?

Here is my code:

// cron-job.js
const cron = require('node-cron');

const scheduler = cron.schedule('* * * * *', () => {
    
    let result = fetchResultAfterSomeOperation();
    if (result < 20) {
        scheduler.stop();  //------------------------ It doesn't work
    }
}, {
    scheduled: false
});

scheduler.start();

Upvotes: 1

Views: 2845

Answers (2)

wael32gh
wael32gh

Reputation: 459

As suggested by @Faizul Ahemed, you may change the code to something like this:

const cron = require('node-cron');
let result = null

const seachFunction = () => {
   if (!result) fetchResults();
}

const scheduler = cron.schedule('*/10 * * * * *', searchFunction, { scheduled: false });

scheduler.start();
setTimeout(() => { scheduler.stop() }, 5 * 60 * 1000)

The above code will cause the fetchResults function to fetch/get data every x time for a duration of y set by the setTimeout.

Upvotes: 1

Faizul Ahemed
Faizul Ahemed

Reputation: 66

How cron jobs created ?

Actually, Cron jobs are created from parent process. So parent process can have ability or feature to kill or suspend the child processes. So here node-cron may works in this way.

Now come to your issue, you have submitting cron task using cron.schedule(time,callback). Now callback is going to run on separate child process. So even if you're using scheduler object to stop the cron task, it wont work. The scheduler can stop the child process from main process (i.e cron.js file).

So I advise you to refactor your code.

Upvotes: 1

Related Questions