仅在一天中的特定时间以设置的间隔运行函数

Run function at set interval only at certain time of the day

本文关键字:设置 函数 运行 定时间 一天      更新时间:2023-09-26

我目前正以规律的时间间隔全天候运行一个函数。

setInterval( function(){ do_this(); } , 1000*60);

不幸的是,这并不是我想要的。我希望这个功能只在早上9点到18点之间以固定的时间间隔运行。该函数不应在这些时间之外运行。如何在node.js中做到这一点?是否有方便使用的模块或功能?

您只需检查当前时间是否在所需的时间范围内,然后用它来决定是否执行您的函数。

setInterval( function(){ 
    var hour = new Date().getHours();
    if (hour >= 9 && hour < 18) {
        do_this(); 
    }
} , 1000*60);

这将在9:00到18:00之间每分钟运行一次您的功能。

您正在使用什么特定的框架吗?

如果我们像这样抽象,那么您很可能希望使用类似cronjob的东西。有一个模块:https://github.com/ncb000gt/node-cron

你想要的模式:

00 00 9-18 * * *-这将在9-18之间每小时运行一次,时间正好为0分0秒。

检查do_this函数中的当前小时数。

function do_this(){
    var now = new Date();
    var currentHour = now.getHours();
    if(currentHour < 9 && currentHour > 18) return;
    //your code
}
setInterval( function(){ do_this(); } , 1000*60);