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替换通用 db
,Redis等。
Replace the generic db
with MongoDB, CouchDB, Redis, etc.
这篇关于node.js中的Cronjobs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文