Search code examples
javascriptnode.jscronnode-schedule

node-schedule: Cannot read property of undefined when restarting job


I am using node-schedule to schedule jobs on my node server, I do it like this:

jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url)));

This works fine. On the set date, the end_auction function executes correctly. Every time I start my server, I retrieve the current auctions from the database and create jobs for them so that they persist if the server was to crash. I do it like so:

var now = new Date();
for(var i = 0; i < plates.length; i++){
    if(now >= plates[i].expires_on){
        end_auction(plates[i].url);
    }else{
        jobs.push(schedule.scheduleJob(new Date(plates[i].expires_on), () => end_auction(plates[i].url)));
    }
}

However, my problem is that every job which is created with the above method fails to execute correctly. At the set time, instead of calling the end_auction function, I will instead get this error:

Cannot read properties of undefined (reading 'url') which points to plates[i].url

I can read the properties of plates just fine using console.log() so I am not sure what the issue is. Can anyone assist me with this? Thanks.


Solution

  • This may be because your "plates" array value has been changed after scheduling the job. To use current data in the future job you can use binding in the callback function as per node-schedule documentation.

    const schedule = require('node-schedule');
    const date = new Date(2012, 11, 21, 5, 30, 0);
    const x = 'Tada!';
    const job = schedule.scheduleJob(date, function(y){
      console.log(y);
    }.bind(null,x));
    x = 'Changing Data';
    

    This will log 'Tada!' when the scheduled Job runs, rather than 'Changing Data', which x changes to immediately after scheduling.