1

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();
Abhishek Pankar
  • 723
  • 8
  • 26
  • Is fetchResultAfterSomeOperation() async? If so, then it's returning a promise and the ```if``` statement would not execute. If this is the case, use await and make your anonymous function async, such as async () => {}. Also, make sure the return from result is not undefined. That also invalidates the ```if``` statement. – moredrowsy Jun 11 '21 at 20:02
  • No, it is not async...what I'm telling is...the control goes into the if statement but `scheduler.stop()` does not work and I don't know why is it not working. – Abhishek Pankar Jun 12 '21 at 04:29
  • Updated the question for easy understanding – Abhishek Pankar Jun 12 '21 at 11:44

2 Answers2

1

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.

1

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.

wael32gh
  • 324
  • 5
  • 11
  • I've tried with `setTimeout` and it is working. Also as @Faizul said that cron-jobs are executed as a child process but how setTimeout is able to stop the process. Can you explain the relation between the setTimeout and child process? – Abhishek Pankar Jan 05 '22 at 12:28