Search code examples
node.jscroncron-task

Schedule a cron once in every 2 years in node js


I want to schedule a script to run once in every 2 years. Could anyone please help me in getting this cracked. I couldn't find the field to add the year.


Solution

  • Most cron schedulers won't parse a year component, I don't know of any that will do this for Node.js.

    You can however emulate this behavior quite readily by checking the year when running the cron function to be fired.

    For example, using the excellent cron module:

    const CronJob = require("cron").CronJob;
    // Fire on July 6th at 11:42
    const cronExpression ="42 11 6 6 *";
    
    const cronJob = new CronJob(
        cronExpression,
        cronFunction
    );
    
    // Return true if the proc. should fire on the year in question.
    // In the example below it will fire on even years.
    function yearFilter(year) { 
        return (year % 2) === 0;
    }
    
    function cronFunction() {
        if (!yearFilter(new Date().getFullYear())) {
            return;
        }
        // Do whatever below...
        console.log("cronFunction: Running....");
    }
    
    // Get the next dates the job will fire on...
    const nextDates = cronJob.nextDates(10);
    console.log("Next dates the job will run on:", nextDates.filter(d => yearFilter(d.year())).map(d => d.format("YYYY-MM-DD HH:mm")));
    
    cronJob.start();
    

    In this example we also print the next 5 dates the job will fire on.

    In this example:

    Next dates the job will run on: [
      '2022-07-06 11:42',
      '2024-07-06 11:42',
      '2026-07-06 11:42',
      '2028-07-06 11:42',
      '2030-07-06 11:42'
    ]