我需要一个 Nodejs 调度程序,允许在不同的间隔任务

我正在寻找一个节点作业计划,它将允许我在不同的时间间隔安排一些任务。比如说,

  • 每30秒调用函数 A
  • 每60秒调用函数 B
  • 每7天调用 C 函数一次

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

到目前为止,我看到:

我发现后者的句法令人困惑。

165290 次浏览

我建议使用 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 e.g. GET request http.get() etc.
console.info('cron job completed');
});
cronJob.start();

您可以在 Node-cron wiki 中找到更多的例子

有关 cron 配置的更多信息可以在 Cron wiki 上找到

我已经在许多项目中使用了这个库,它起到了作用。我希望它能有所帮助。

我用过 Node-cron议程

Node-cron 是一个非常简单的库,它提供了非常基本和容易理解的 API,比如 crontab。它不需要任何配置,只是工作。

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

Protocol 非常强大,适用于更复杂的服务。想想 快点,您必须运行数百万个任务。议程是最好的选择。

注意: 您需要使用 蒙哥布议程

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

我已经编写了一个节点模块,它使用 moment 长度提供了一个声明性接口,为 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);

我认为最好的排名是

节点调度

2. 稍后

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

也许你可以从 节点模块中找到答案。

为此,我编写了一个名为 一个 href = “ https://www.npmjs.com/package/timexe”rel = “ nofollow norefrer”> timexe 的小模块:

  • 它的代码简单,可靠性低,并且没有依赖关系
  • 分辨率以毫秒为单位,并且随着时间的推移具有很高的精度
  • 与 Cron 类似,但不兼容(逆序和其他改进)
  • 我也在浏览器上工作

安装:

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

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