Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

node.js - How to stop a node cron job

I want to stop a node cron job on certain conditions.

This is how I started the task to run every 1 second.

const runScheduler = (url)=>{
    cron.schedule('*/1 * * * * *', () => {
        console.log('running a task every one second');
        async.waterfall([ getUrlDelay(url), dbMethods.updateUrlResponses(url) ],function(err, success){
            if(err) return console.log('Url Not Found');
        })
      });
}

I want to stop this job but unable to do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The below answer may not be relevant now because of the changes done to these packages. The scheduleJob was meant to be a pseudocode to just create a job. The objective was to show how to stop them.


Here's a comprehensive summary for instantiating, starting and stopping sheduled cron-jobs for three cron-modules (cron, node-cron & node-schedule):

1. CRON

In order to cancel the job you can create a job with unique name.

var cron = require('cron').CronJob;

var j = cron.scheduleJob(unique_name, '*/1 * * * * *',()=>{
    //Do some work
});
// for some condition in some code
let my_job = cron.scheduledJobs[unique_name];
my_job.stop();

It should cancel the job.

2. NODE-CRON

var cron = require('node-cron');

const url_taskMap = {};
const task = cron.schedule('*/1 * * * * *',()=>{
    //Foo the bar..
});
url_taskMap[url] = task;
// for some condition in some code
let my_job = url_taskMap[url];
my_job.stop();

3. NODE-SCHEDULE

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

let uniqueJobName = specificURL;
// Shedule job according to timed according to cron expression
var job = schedule.scheduleJob(uniqueJobName,'*/10 * * * * *', function(){
     //Bar the foo..
});
// Inspect the job object (i.E.: job.name etc.)
console.log(`************** JOB: ******************`);
console.log(job);

// To cancel the job on a certain condition (uniqueJobName must be known) 
if (<someCondition>) {
    let current_job = schedule.scheduledJobs[uniqueJobName];
    current_job.cancel();
}

Summarized by Aritra Chakraborty & ILuvLogix


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...