如何让代码在每个周末执行?
How to make code execute at each week end?
我想每个星期天执行一段代码23:59(晚上11点)(基本上是每个周末)。但是,它应该每周只触发一次。
setInterval()
函数不会在这里删除它,因为应用程序可能会同时重新启动。
如果这无论如何都有帮助,我有这个基本想法:
Set an interval (with setInterval
) for every 5-10 seconds and check if it's Sunday and hour 23 (11 pm). However, this solution will be inconsistent and may fire more than once a week. I need a more bullet-proof solution to this.
您可以使用任何 cron 模块(例如 https://www.npmjs.com/package/cron) and set job for 59 23 * * 0
(ranges)
const { CronJob } = require('cron');
const job = new CronJob('59 23 * * 0', mySundayFunc);
job.start();
如何计算开始时的剩余时间,就像这段代码
const WEEK_IN_MS = 604800000;
const ONE_HOUR_IN_MS = 3600000;
const FOUR_DAYS_IN_MS = 4 * WEEK_IN_MS / 7;
function nextInterval() {
return WEEK_IN_MS - ((Date.now() + FOUR_DAYS_IN_MS) % WEEK_IN_MS) - ONE_HOUR_IN_MS;
}
const interval = nextInterval();
console.log(`run after ${interval} ms`);
setTimeout(
() => console.log('Do it!!!'),
interval
)
我想每个星期天执行一段代码23:59(晚上11点)(基本上是每个周末)。但是,它应该每周只触发一次。
setInterval()
函数不会在这里删除它,因为应用程序可能会同时重新启动。
如果这无论如何都有帮助,我有这个基本想法:
Set an interval (with
setInterval
) for every 5-10 seconds and check if it's Sunday and hour 23 (11 pm). However, this solution will be inconsistent and may fire more than once a week. I need a more bullet-proof solution to this.
您可以使用任何 cron 模块(例如 https://www.npmjs.com/package/cron) and set job for 59 23 * * 0
(ranges)
const { CronJob } = require('cron');
const job = new CronJob('59 23 * * 0', mySundayFunc);
job.start();
如何计算开始时的剩余时间,就像这段代码
const WEEK_IN_MS = 604800000;
const ONE_HOUR_IN_MS = 3600000;
const FOUR_DAYS_IN_MS = 4 * WEEK_IN_MS / 7;
function nextInterval() {
return WEEK_IN_MS - ((Date.now() + FOUR_DAYS_IN_MS) % WEEK_IN_MS) - ONE_HOUR_IN_MS;
}
const interval = nextInterval();
console.log(`run after ${interval} ms`);
setTimeout(
() => console.log('Do it!!!'),
interval
)