How to schedule cron job in nodejs for a time range

Viewed 234

I am trying to schedule a Cron Job between 9AM to 9PM for every 15 minutes. I am able to schedule it for every 15 minutes, but not for the time duration. Below is the code snippet

const CronJob = require('cron').CronJob
const splunkNode = require('./splunk_node')
let job = new CronJob("*/15 08-21 * * * 1-5", function(){
    console.log('ran at ', new Date())
// CRON JOB()
 },function(){
     console.log('Job stopped')
 },true,'America/Los_Angeles')
 job.start()

Does the syntax for specifying range has to be enclosed between brackets[]?

1 Answers

A lil workaround is to schedule a function that calls itself after a certain amount of time

function callCronJob (){
const job = new CronJob("*/15 08-21 * * * 1-5", function(){
    // if time range we are in doesn't fall between 9AM and 9PM cancel this job and call // this function again with it's 9AM 
// next part is pseduocode cause I am lazy to write actual code
  if ( 9am >timeRange > 9pm ){
 job.cancel() 
 new cronJob(timeRange+ 12 hours , ()=>{
   callCronJob();
});
 return;
}
// CRON JOB()
 },function(){
     console.log('Job stopped')
 },true,'America/Los_Angeles')
 job.start()
}
Related