如何在特定时间运行功能日期?

编程入门 行业动态 更新时间:2024-10-12 05:44:57
本文介绍了如何在特定时间运行功能日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在给定的时间和日期运行函数?

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); })(); }

更多推荐

如何在特定时间运行功能日期?

本文发布于:2023-11-27 14:16:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   功能   时间   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!