21

I am planning on using node-schedule to set up push notifications for appointment reminders as follows:

var schedule = require('node-schedule');
var date = req.body.date;   // Date for reminder from client request 
var j = schedule.scheduleJob(date, function(){
    // Send push notification
});

Now I know you can cancel the event by calling cancel():

j.cancel()

However, how can I refer to that specific job to cancel if the user from the client side decides to change the appointment to a different date?

Thanks in advance for your help!

ShahNewazKhan
  • 1,057
  • 1
  • 12
  • 26

2 Answers2

39

In order to retrieve a specific job, you could create it with a unique name and you can retrieve it later via that unique name:

var j = schedule.scheduleJob(unique_name, date, function() {
});
// later on
var my_job = schedule.scheduledJobs[unique_name];
my_job.cancel();
ShahNewazKhan
  • 1,057
  • 1
  • 12
  • 26
  • 4
    this worked beautifully. thank you. i was trying to serialize the job object, write it into my db, retrieve it, deserialize it and the call .cancel(). you can imagine my pain. – kalin Oct 01 '16 at 00:14
  • \0/ that's awesome! – ShahNewazKhan Dec 14 '16 at 00:23
  • It is very helpful after 2 years as well. Thanks a lot. – Sudarshana Dayananda Oct 27 '18 at 12:06
  • @ShahNewazKhan it seems it doesn't work with node-schedule version 1.3.2. if there is a unique_name parameter, function is not called at specified date at all. with which version it works? also i can't find unique name as first parameter in doc. – user006779 May 26 '19 at 17:02
0
var randf = require('randomstring');    
    var jobId = randf.generate(10); //randomsrting
    var at = new Date();
    var time = at.setSeconds(at.getSeconds() + Number(5))  //after 5 second     
    schedule.scheduleJob(jobId, new Date(time),function(){
         schedule.cancelJob(jobId);
         console.log('hi--viral');
     });
Viral Patel
  • 921
  • 10
  • 11