Search code examples
javascriptnode.jscronagenda

How do I run cron-like job at certain date time in the future using Agenda in Nodejs


I have a problem here. How do i run job at certain date time in the future using Agenda like node-scheduler do. Based on https://www.npmjs.com/package/node-schedule, node-schedule have cron-style scheduling method. So it is easier for me to extract date from my input. I have read Agenda documentation https://github.com/rschmukler/agenda#agenda-events, it says Agenda uses Human Interval for specifying the intervals.

Cron

How can i do this?


Solution

  • If you have a future date, you can convert this to number of days from today or even number of seconds as below and then use the same with agenda cron job

    function findDaysDifference ( date1, date2 ) {
      //Get 1 day in milliseconds
      var oneDay_ms = 1000 * 60 * 60 * 24;
    
      // Convert both dates to milliseconds
      var date1_ms = date1.getTime();
      var date2_ms = date2.getTime();
    
      // Calculate the difference in milliseconds
      var difference_ms = date2_ms - date1_ms;
        
      // Convert back to days and return
      return Math.round(difference_ms/oneDay_ms); 
    }
    
    var futureDate = new Date(2018, 0, 1);
    var daysFromNow = findDaysDifference(new Date(), futureDate);
    
    console.log(daysFromNow);

    Then create agenda job and schedule it with daysFromNow calculated above,

    agenda.define('sayHello', function(job) {
      console.log("Hello!");
    });
    
    // Schedule a job to run once at a given time
    agenda.schedule(daysFromNow + ' days', 'sayHello');
    

    If you want to schedule it at particular time in the future, you can calculate the seconds as below,

    function findSecondsDifference ( date1, date2 ) { 
          var oneSecond_ms = 1000;
      
          // Convert both dates to milliseconds
          var date1_ms = date1.getTime();
          var date2_ms = date2.getTime();
    
          // Calculate the difference in milliseconds
          var difference_ms = date2_ms - date1_ms;
            
          // Convert back to days and return
          return Math.round(difference_ms/oneSecond_ms); 
        }
    
        var futureDate = new Date(2018, 0, 1, 16);
        var secsFromNow = findSecondsDifference(new Date(), futureDate);
    
        console.log(secsFromNow);

    Then create agenda job and schedule it with secsFromNow calculated above,

    agenda.define('sayHello', function(job) {
      console.log("Hello!");
    });
    
    // Schedule a job to run once at a given time
    agenda.schedule(secsFromNow + ' seconds', 'sayHello');