我有一个JSON的任务组合在一个区间(参见unit
),它们应该every
unit
的{{1}}间隔重复。
items=[
{
"unit" : "minute",
"detail" :
[
{"every" : 3, task : "task1"}
{"every" : 4, task : "task2"}...
]
},
{
"unit" : "day",
"detail" :
[
{"every" : 3, task : "task3"}
{"every" : 4, task : "task4"}...
]
},..
]
我使用node-cron通过跟踪异步函数在每个every
unit
的时间间隔上安排它们,例如:task1应该每3分钟开心一次。
我试过这段代码:
var CronJob = require('cron').CronJob;
function cronify(callback)
{
for (var i in items)
{
for (var j in items[i].detail) {
callback(items[i].unit,items[i].detail[j]);
}
}
}
cronify(function (duration, detail) {
var when = '* * * * * *';
switch(duration)
{
case 'minute' :
when = '* */'+detail.every+' * * * *';
break;
case 'hour' :
when = '* * */'+detail.every+' * * *';
break;
case 'day' :
when = '* * * * */'+detail.every+' * *';
break;
}
var job = new CronJob(when, function () {
//Do the task for task
}, null, true, "GMT");
}
});
但问题是每一项任务每秒执行一次,与unit
和every
提到的持续时间无关。
答案 0 :(得分:2)
是的,如果你把星号(*)放在第二位,那么在* * / 2 * * * *的情况下,任务将每隔几分钟执行一次。要在一分钟内运行一次任务,您可以在0秒内输入0,而不是0 * / 2 * * * *。示例代码:
items = [{
"unit": "minute",
"detail": [{
"every": 3,
"task": "task1"
}, {
"every": 4,
"task": "task2"
}]
}, {
"unit": "day",
"detail": [{
"every": 3,
task: "task3"
}, {
"every": 4,
task: "task4"
}]
}];
var CronJob = require('cron').CronJob;
function cronify(callback) {
for (var i in items) {
for (var j in items[i].detail) {
callback(items[i].unit, items[i].detail[j]);
}
}
}
cronify(function(duration, detail) {
var when = '* * * * * *';
switch (duration) {
case 'minute':
when = '0 */' + detail.every + ' * * * *';
break;
case 'hour':
when = '0 0 */' + detail.every + ' * * *';
break;
case 'day':
when = '0 0 0 0 */' + detail.every + ' *';
break;
}
var job = new CronJob(when, function (when) {
console.log(when);
}, null, true, "GMT");
});