运行 仅在一天中的特定时间按设定的时间间隔运行

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

我目前运行全天候定期执行一项功能。

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

不幸的是,这不是我想要的。我希望此功能仅在从早上 0900 点到 1800 点的固定时间间隔内 运行。该函数不应 运行 在这些时间之外。如何在 node.js 中完成此操作?有没有方便使用的模块或功能?

有没有你正在使用的特定框架?

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

你想要的图案:

00 00 9-18 * * * - 这将是 运行 每小时 9-18 点正好是 0 分 0 秒。

您可以简单地检查当前时间是否在所需的时间范围内,并以此来决定是否执行您的功能。

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

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

检查 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);