How to cancel all cron job?

Viewed 370

I have a nodejs app that I didn't code myself with an active cron job. The app uses cron (not node-cron). I need to cancel the job but I didn't have the Id nor the name of the job. Only this :

const job = new cron.CronJob("00 00 13 * * 0", async () => { 
// code inserted here
 });
job.start();

How can I force all jobs to stop ?

1 Answers

You can use job.Stop() to stop the job that is running. You'll need to store each job reference so you can stop it later on when you need to, in the example below I store the jobs in an array.

You can also set a handler to run when the job is stopped, perhaps to clean things up, or log that the job has been stopped successfully.

const cron = require('cron');

// Start some jobs running...
let jobCount = 5;
const jobs = Array.from( { length: jobCount }, (v, k) => new cron.CronJob('*/2 * * * * *', () => {
    console.log(`Sample cron job #${k+1} running...`);
}, () => console.log(`Job #${k+1} stopped.`), false));


// Start the cron job...
jobs.forEach(job => job.start());

// Stop job after 5 seconds...
setTimeout(() => {
    console.log("Stopping cron jobs..");
    // Kill the cron job
    jobs.forEach(job => job.stop());
}, 5000)
Related