Javascript 每天午夜运行一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26306090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running a function everyday midnight
提问by wap300
walk.on('dir', function (dir, stat) {
uploadDir.push(dir);
});
I am using Node, and i need make this function run everyday at midnight, this is possible?
我正在使用 Node,我需要让这个函数每天在午夜运行,这可能吗?
回答by wap300
I believe the node-schedule packagewill suit your needs. Generally, you want so-called cronto schedule and run your server tasks.
我相信node-schedule 包将满足您的需求。通常,您希望所谓的cron来安排和运行您的服务器任务。
With node-schedule:
使用节点计划:
import schedule from 'node-schedule'
schedule.scheduleJob('0 0 * * *', () => { ... }) // run everyday at midnight
回答by Donal
回答by TinkerTank
I use the following code:
我使用以下代码:
function resetAtMidnight() {
var now = new Date();
var night = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1, // the next day, ...
0, 0, 0 // ...at 00:00:00 hours
);
var msToMidnight = night.getTime() - now.getTime();
setTimeout(function() {
reset(); // <-- This is the function being called at midnight.
resetAtMidnight(); // Then, reset again next midnight.
}, msToMidnight);
}
I think there are legitimate use-cases for running a function at midnight. For example, in my case, I have a number of daily statistics displayed on a website. These statistics need to be reset if the website happens to be open at midnight.
我认为在午夜运行函数有合法的用例。例如,就我而言,我在网站上显示了许多每日统计数据。如果网站恰好在午夜开放,则需要重置这些统计信息。
Also, credits to thisanswer.
此外,归功于此答案。
回答by Jason
Is this a part of some other long-running process? Does it really need to be? If it were me, I would just write a quick running script, use regular old cron to schedule it, and then when the process completes, terminate it.
这是其他一些长期运行过程的一部分吗?真的有必要吗?如果是我,我只会写一个快速运行的脚本,使用常规的旧 cron 来调度它,然后当进程完成时,终止它。
Occasionally it will make sense for these sorts of scheduled tasks to be built into an otherwise long-running process that's doing other things (I've done it myself), and in those cases the libraries mentioned in the other answers are your best bet, or you could always write a setTimeout()or setInterval()loop to check the time for you and run your process when the time matches. But for most scenarios, a separate script and separate process initiated by cron is what you're really after.
有时,将这些类型的计划任务构建到一个长期运行的进程中是有意义的,该进程正在做其他事情(我自己已经完成了),在这些情况下,其他答案中提到的库是你最好的选择,或者您总是可以编写一个setTimeout()orsetInterval()循环来检查您的时间并在时间匹配时运行您的流程。但对于大多数情况,您真正想要的是由 cron 启动的单独脚本和单独进程。

