我如何在将来的某个日期时间使用 Nodejs 中的 Agenda 运行 类似 cron 的工作

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

我这里有问题。我如何 运行 在将来的某个日期时间使用节点调度程序那样的议程来工作。基于 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,它表示 Agenda 使用 Human Interval 来指定间隔。

我该怎么做?

如果您有未来的日期,您可以将其转换为从今天开始的 days 的数量,或者如下所示的 seconds 的偶数,然后将其与 agenda cron 作业一起使用

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);

然后创建 agenda 作业并使用上面计算的 daysFromNow 安排它,

agenda.define('sayHello', function(job) {
  console.log("Hello!");
});

// Schedule a job to run once at a given time
agenda.schedule(daysFromNow + ' days', 'sayHello');

如果你想安排在未来的特定时间,你可以计算秒数,

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);

然后创建 agenda 作业并使用上面计算的 secsFromNow 安排它,

agenda.define('sayHello', function(job) {
  console.log("Hello!");
});

// Schedule a job to run once at a given time
agenda.schedule(secsFromNow + ' seconds', 'sayHello');

与Agenda.js

interval can be a human-readable format String, a cron format String, or a Number.

意味着它支持 cron 风格的调度方法

例如

you could schedule a job to run 3 minutes from the current time

  await agenda.schedule('3 minutes', 'send confirmation to new user', {email:"newuser@mal.com"} );

  // Alternatively, you could also do:
  await agenda.schedule('*/3 * * * *', 'send confirmation to new user', {email:"newuser@mal.com"});
   

run a job Monday at 09:00

   await agenda.schedule('0 9 * * 1', 'MondayJob', {msg:"guess what today is 'Monday'"});

run on Saturday at 23:45 (11:45 PM)

await agenda.schedule('45 23 * * 6', 'jobName', {});