node.jscron

Run cron at 11 30 AM alternating days


I want a cron job for NodeJS that runs at 11:30 AM alternating days. I searched but I get solutions only for daily, not any solution for every other day.

ChatGPT suggested

const isAlternateDay = () => {
  const today = new Date();
  const day = today.getDate();
  // For example, consider odd days as alternate days
  return day % 2 !== 0;
};

// Schedule the cron job for 11:30 AM every day
cron.schedule('30 11 * * *', () => {
  if (isAlternateDay()) {
    console.log('Running cron job on an alternate day at 11:30 AM');
    // Your task logic here
  }
});

But I want to do this using cron itself; I do not want to add an external condition.


Solution

  • To schedule a cron job that runs alternative days at 11:30 AM, you can use the following cron expression:

    // Schedule a task to run alternative days at 11:30 AM
    cron.schedule('30 11 */2 * *', () => {
      console.log('Running a task alternative days at 11:30 AM');
    
    });
    

    Explanation: