James111 James111 - 1 month ago 8
Node.js Question

node-schedule how can I access the current rule which is being executed?

I've got node-schedule setup to create multiple cron jobs, these cron jobs are created dynamically in a loop. The code inside the schedule.scheduleJob callback needs to access to the current Rule which is being executed.

So if I had a cron running every 1, 2, and 3 minutes, I'd want access to the rule so it'd tell me that my 1 minute cron is running now.

// Create new cron for each iteration (creating 1-10 mins)
for (var x = 1; x<10; x++){
var rule = new schedule.RecurrenceRule();
rule.minute = new schedule.Range(0, 59, x);
schedule.scheduleJob(rule, (RULE_SHOULD_ BE_HERE) => {
// Can I access the RULE which is being executed NOW somehow?!
functionThatRunsEveryX(rule.minute.step);
});
}


I would think I'd be able to access the rule via the callback constructor! Is there a way to do this

Answer

The way I fixed this was to create an object, assign the schedule to that object and then create a property on the object which holds the rule.

Like so:

for (var x = 1; x<10; x++){
  var rule = new schedule.RecurrenceRule();
  rule.minute = new schedule.Range(0, 59, x);
  // Do not use ()=> fat arrow, we need access to this of job
  var job = schedule.scheduleJob(rule, function () {
    // Must use this to access rule
    functionThatRunsEveryX(this.rule.minute.step);
  });
  job.rule = rule; 
  // Assign more values here if you wish job.foo = bar
}

You shouldn't use the fat arrow ()=> {, instead you must use the normal function () { way of creating a function. If you use the fat arrow method, you won't have access to the job.rule via this.rule.

Comments