简体   繁体   English

仅在一天的特定时间以设置的间隔运行功能

[英]Run function at set interval only at certain time of the day

I am currently running a function at regular interval round the clock. 我目前正在全天候定期运行一个函数。

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

Unfortunately, this is not exactly what I want. 不幸的是,这并不是我想要的。 I would like this function to be run at set regular interval from morning 0900hrs to 1800hrs only. 我希望此功能仅在从上午0900hrs到1800hrs的固定时间间隔运行。 The function should not run outside of these hours. 该功能不应在这些时间之外运行。 How can this be done in node.js? 如何在node.js中完成? Are there convenient modules or functions to use? 是否有方便使用的模块或功能?

You can simply just check to see if the current time is within the desired time range or not and use that to decide whether to execute your function or not. 您只需检查当前时间是否在期望的时间范围内,然后使用它来决定是否执行您的功能。

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

This will run your function every minute between the hours of 9:00 and 18:00. 这将在9:00和18:00之间的每分钟运行一次功能。

Is there any specific framework you are working with? 您正在使用任何特定的框架吗?

If we're as abstract as this, you would most likely want to use something like a cronjob. 如果我们像这样抽象,那么您很可能想要使用诸如cronjob之类的东西。 There's a module for that: https://github.com/ncb000gt/node-cron 有一个用于此的模块: https : //github.com/ncb000gt/node-cron

The pattern for what you want: 您想要的模式:

00 00 9-18 * * * - This will be ran each hour between 9-18 at exactly 0 minutes and 0 seconds. 00 00 9-18 * * * -每小时将在9-18之间的0时0分运行。

Check for the current hour inside your do_this function. 检查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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM