2

Using node-scheduler to set up recurring job. I need 7 days a week at several specific times - e.g. 5:45am, 06:30am, 11:15am, etc.

I set up rule:

let rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [1,2,3,4,5,6,7]

Now if I add hours and minutes as arrays it looks like they run through all hours for all minutes - e.g.

rule.hour = [5,6,11];
rule.minute = [45,30,15];

So, this will run at 5:45am, 6:45am, 11:45am, 5:30am, 6:30am, 11:30am, ....

How can I use rules to set up for exact times? Again, in my example 5:45am, 06:30am, 11:15am

rfossella
  • 107
  • 1
  • 3
  • 11

2 Answers2

4

Another approach is to use Object Literal Syntax. If the weekday is not specified as shown below the times apply for being scheduled each day.

let times = [
  {hour: 5, minute: 45}, 
  {hour: 6, minute: 30}, 
  {hour: 11, minute: 15}
];
times.forEach(function(time) {
  var j = schedule.scheduleJob(time, function() {
    // your job
    console.log('Time for tea!');
  });
})

Marcus
  • 1,097
  • 11
  • 21
2

The node-schedule module seems to support cron syntax. But as the schedule you want, cannot be expressed in a single rule with cron, you also can't define that in a single rule in node-schedule. Using the dayOfWeek, hour and minute definitions for the rule schedules the job on every combination of day, hour and minute, like a cron rule does.

Have a look at the recurrence rule scheduling section in the docs, how to define a rule for a specific time every day, and create and schedule a separate rule for each time you need

let hour = [5, 6, 11];
let minute = [45, 30, 15];

for (let i = 0; i < hour.length; i++) {
  let rule = new schedule.RecurrenceRule();
  rule.dayOfWeek = [0, 1, 2, 3, 4, 5, 6];
  rule.hour = hour[i];
  rule.minute = minute[i];

  let j = schedule.scheduleJob(rule, function(){
    //your job
  });
}
derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • Thanks for the feedback. I originally set it up similar to the the code you both offered above but was trying to get it all into a single rule. I visually display the jobs with their next invocation in a table and preferred a single job (name) to list in the table. I'm going to research a bit more and post back here if I come up w/anything else. Thanks again for the prompt feedback! – rfossella Mar 30 '19 at 07:39