Writing a reschedulable cron job in Node.js

4k views Asked by At

I am using node-schedule node package to write the cron job. I am able to write a simple schedular but what I want is a reschedulable job.

In my app, users can start a task for a specific date. Now I can acheive this easily by below code.

var schedule = require('node-schedule');
var date = new Date(2012, 11, 21, 5, 30, 0);

var j = schedule.scheduleJob(date, function(){
  console.log('Do something on scheduled date');
});

The problem I've is how I can reschedule a selected scheduled job.

Let's say, if user A started a job to run on date 10/14/2017 and so I created a new cron job to run on date 10/14/2017. But now user A decides to change the task date to 1/14/2017, then how would I identify the task created by user A out of the multiple tasks already in queue (created by other users) and then reschedule that cron job to the new date i.e. 1/14/2017?

1

There are 1 answers

0
Trevor Dixon On BEST ANSWER

j has a reschedule method you can call. See https://www.npmjs.com/package/node-schedule#jobreschedulespec.

j.reschedule(new Date);

To keep track of jobs, you might use an object to map a user to a scheduled job.

const userJobs = {};

userJobs['user A'] = schedule.scheduleJob(date, () => {
  console.log('Do something on scheduled date');
  delete userJobs['user A'];
});

userJobs['user A'].reschedule(new Date);