node.js 中的 Cronjobs [英] Cronjobs in node.js
本文介绍了node.js 中的 Cronjobs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能在 node.js 中在一天中的特定时间定期调用函数?我的第一个实现是
Is there a possibility to periodically call functions at a specific time of the day in node.js? My first implementation was
setInterval(functionName(),(24*60*60*1000));
这是次优的,因为每次我重新启动节点时它都会重新启动.是否有更好的可能性来实现这一点?
This is suboptimal, because it will restart every time I restart node. Are there better possibilities to implement this?
推荐答案
为了防止重启,您需要创建一个持久的数据存储作业.
To guard against restarts you need to create a persistent data stored job.
类似:
Job = {
_id: Number,
job: String,
dueDate: Date,
completed: Boolean
}
然后有一些代码如下:
var createJob = function(url, date) {
var j = db.create(Job, function(j) {
j.job = url;
j.dueDate = date;
j.save();
});
};
var runJob = function(j) {
var id = j._id;
setInterval(j.dueDate - Date.now(), function() {
db.getOne(Job, { _id : id }, function(j) {
require(j.job);
j.finished = true;
j.save();
});
});
j = null;
};
在启动时,您只需要执行以下操作:
On start up you just have to do something like :
db.get(Job, { finished: false }, function(jobs) {
jobs.forEach(runJob);
});
用 MongoDB、CouchDB、Redis 等替换通用的 db
Replace the generic db
with MongoDB, CouchDB, Redis, etc.
这篇关于node.js 中的 Cronjobs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文