我需要一个Nodejs调度器,允许在不同的时间间隔

我正在寻找节点工作时间表,这将允许我安排在不同的时间间隔的任务。 例如,

  • 每30秒调用一次functionA.
  • 每60秒调用一次functionB.
  • 每7天调用一次C函数

我也希望能够启动和停止这个过程。

到目前为止,我已经看过:

  • 后来 – 语法混淆了我,显然你不能安排超过一个月的任务

  • 议程 – 似乎是最有前途的,但是我对数据库function感到困惑

  • 时间计划 – 太简单,无法启动和停止

我发现后者的语法混乱。

我会推荐node-cron 。 它允许使用Cron模式运行任务,例如

 '* * * * * *' - runs every second '*/5 * * * * *' - runs every 5 seconds '10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute '0 * * * * *' - runs every minute '0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds) 

但也更复杂的时间表,如

 '00 30 11 * * 1-5' - Runs every weekday (Monday through Friday) at 11:30:00 AM. It does not run on Saturday or Sunday. 

示例代码 :每10分钟运行一次作业:

 var cron = require('cron'); var cronJob = cron.job("0 */10 * * * *", function(){ // perform operation eg GET request http.get() etc. console.info('cron job completed'); }); cronJob.start(); 

你可以在node-cron wiki中find更多的例子

有关cronconfiguration的更多信息可以在cron wiki上find

我已经在许多项目中使用过这个库,并且完成了这项工作。 我希望这会有所帮助。

我已经使用了node-cron和议程 。

node-cron是一个非常简单的库,它提供了像crontab一样简单易懂的api。 它不需要任何configuration,只是工作。

 var cronJob = require('cron').CronJob; var myJob = new cronJob('00 30 11 * * 1-5', function(){...}); myJob.start(); 

议程非常强大,适合更复杂的服务。 想想看,你必须运行数百万个任务。 议程将是最好的select。

注意:您需要Mongodb来使用Agenda

 var Agenda = require("Agenda"); var agenda = new Agenda({db: { address: 'localhost:27017/agenda-example'}}); agenda.every('*/3 * * * *', 'delete old users'); agenda.start(); 

我已经写了一个节点模块,它提供了一个使用瞬间持续时间提供声明接口的setInterval封装:

npm安装每一刻

 var every = require('every-moment'); var timer = every(5, 'seconds', function() { console.log(this.duration); }); every(2, 'weeks', function() { console.log(this.duration); timer.stop(); this.set(1, 'week'); this.start(); }); 

https://www.npmjs.com/package/every-moment

https://github.com/raygerrard/every-moment

nodeJS默认

https://nodejs.org/api/timers.html

 setInterval(function() { // your function }, 5000); 

我认为最好的排名是

1.node时间表

2.later

3.crontab

节点时间表的样本如下:

 var schedule = require("node-schedule"); var rule = new schedule.RecurrenceRule(); //rule.minute = 40; rule.second = 10; var jj = schedule.scheduleJob(rule, function(){ console.log("execute jj"); }); 

也许你可以从节点模块find答案。

我已经写了一个小模块来做到这一点。 你可以在这里find它:
https://github.com/paragi/timexe.git
https://www.npmjs.com/package/timexe

一些function:

  • 它简单,可靠的代码小,没有依赖关系
  • 分辨率以毫秒为单位,随着时间的推移精度很高
  • 克朗喜欢,但不兼容(颠倒顺序和其他改进)
  • 我也在浏览器中工作

安装:

 npm install timexe 

使用:

 var timexe = require('timexe'); //Every 30 sec var res1=timexe(”* * * * * /30”, function() console.log(“Its time again”)}); //Every minute var res2=timexe(”* * * * *”,function() console.log(“a minute has passed”)}); //Every 7 days var res3=timexe(”* y/7”,function() console.log(“its the 7th day”)}); //Every Wednesdays var res3=timexe(”* * w3”,function() console.log(“its Wednesdays”)}); // Stop "every 30 sec. timer" timexe.remove(res1.id); 

您可以通过直接在timexe作业数组中删除/重新添加条目来实现启动/停止function。 但它不是一个明确的function。