【发布时间】:2020-10-26 08:31:01
【问题描述】:
我想安排一个脚本每 2 年运行一次。谁能帮我破解这个问题。我找不到添加年份的字段。
【问题讨论】:
-
你想运行什么样的脚本?它是一个 shell 脚本还是更深奥的东西?
我想安排一个脚本每 2 年运行一次。谁能帮我破解这个问题。我找不到添加年份的字段。
【问题讨论】:
大多数 cron 调度程序不会解析 year 组件,我不知道有任何会为 Node.js 执行此操作。
但是,您可以通过检查运行要触发的 cron 函数的年份来很容易地模拟这种行为。
例如,使用优秀的cron 模块:
const CronJob = require("cron").CronJob;
// Fire on July 6th at 11:42
const cronExpression ="42 11 6 6 *";
const cronJob = new CronJob(
cronExpression,
cronFunction
);
// Return true if the proc. should fire on the year in question.
// In the example below it will fire on even years.
function yearFilter(year) {
return (year % 2) === 0;
}
function cronFunction() {
if (!yearFilter(new Date().getFullYear())) {
return;
}
// Do whatever below...
console.log("cronFunction: Running....");
}
// Get the next dates the job will fire on...
const nextDates = cronJob.nextDates(10);
console.log("Next dates the job will run on:", nextDates.filter(d => yearFilter(d.year())).map(d => d.format("YYYY-MM-DD HH:mm")));
cronJob.start();
在此示例中,我们还打印作业将触发的接下来 5 个日期。
在这个例子中:
Next dates the job will run on: [
'2022-07-06 11:42',
'2024-07-06 11:42',
'2026-07-06 11:42',
'2028-07-06 11:42',
'2030-07-06 11:42'
]
【讨论】: