如何在特定时间运行函数&日期? [英] How to run a function at specific time & date?
问题描述
如何在给定的时间和日期运行函数?
How can I run a function at a given time and date?
示例:我有一个函数需要在每个月的 12 日上午 10 点运行.
Example: I have a function that needs to run on the 12th of each month at 10AM.
如果这很重要,此页面将 24/7 全天候运行.
This page will be running 24/7, if this is important.
显然我必须与当前日期进行比较,但我不确定如何检查当前日期和时间是否匹配.
Obviously I'd have to compare against the current date, but I'm not sure how to check if the current date and time has been matched.
香农
推荐答案
不建议使用 setInterval
,因为它具有非确定性行为 - 事件可能会被错过,或同时触发.时间也会不同步.
It's not advised to use setInterval
because it has non-deterministic behaviour - events can be missed, or fire all at once. Time will fall out of sync, too.
下面的代码改为使用 setTimeout
和 一分钟 时间段,其中计时器每分钟重新同步,以便尽可能接近 hh:mm:00.000s尽可能点.
The code below instead uses setTimeout
with a one minute period, where each minute the timer is resynchronised so as to fall as closely to the hh:mm:00.000s point as possible.
function surprise(cb) {
(function loop() {
var now = new Date();
if (now.getDate() === 12 && now.getHours() === 12 && now.getMinutes() === 0) {
cb();
}
now = new Date(); // allow for time passing
var delay = 60000 - (now % 60000); // exact ms to next minute interval
setTimeout(loop, delay);
})();
}
这篇关于如何在特定时间运行函数&日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!