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

 ̄綄美尐妖づ 提交于 2021-02-08 09:55:48

问题


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. The function should not run outside of these hours. How can this be done in node.js? Are there convenient modules or functions to use?


回答1:


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.




回答2:


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. There's a module for that: 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.




回答3:


Check for the current hour inside your do_this function.

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


来源:https://stackoverflow.com/questions/33605072/run-function-at-set-interval-only-at-certain-time-of-the-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!