无限循环检查时间



例如,假设我想制作一个代码,每天在 8:03 调用console.log()某些东西。我尝试使用无限循环(实际上它是一个每 2 秒调用一次的函数(编写类似的东西,该循环检查是否

timeNow is >= timeToConsoleLog

并在满足条件时调用console.log(),然后递增timeToConsoleLog

代码有效,但我发现它非常丑陋,我想要一些关于如何以更漂亮的方式实现这样的事情的建议。

谢谢

您可以使用node-schedule包,它允许您以 cron 样式调度事件。

在 08:03 运行一次函数将如下所示:

const schedule = require('node-schedule');
schedule.scheduleJob('8 3 * * *', yourFunction) // run every day at 08:03

语法如下:

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

node-cron 可以在这里提供帮助:

var cron = require('node-cron');
cron.schedule('8 3 * * *', function(){
console.log('8:03 everyday.');
});

更多在这里: https://hackernoon.com/nodejs-javascript-cron-cron-jobs-cronjob-reactjs-scheduler-schedule-example-tutorial-25bcbe23bc6b

你只需要对第一个间隔进行计时,剩下的就很容易了:

const DAY = 1000 * 60 * 60 * 24;
function sheduleAt(time, fn) {
const dayBegin = new Date();
dayBegin.setHours(0);
dayBegin.setMinutes(0);
const left = (dayBegin + time - Date.now()) % DAY;
setTimeout(function next() {
fn();
setTimeout(next, DAY);
}, left);
}

可用于:

sheduleAt(12/*h*/ * 60 + 30/*min*/, () => console.log("lunch"));

您需要计算下次必须调用函数的超时。

function callFoo(){
var dateNow  = new Date(),
nextDate = new Date(),
timeout  = 0;
nextDate.setHours(8);
nextDate.setMinutes(3);
if(dateNow > nextDate){
nextDate = new Date(new Date(nextDate).getTime() + (60 * 60 * 24 * 1000));
}
setTimeout(foo, (nextDate - dateNow));
}
function foo(){
callFoo();
console.log('It's time...');
}
callFoo();

最新更新