简体   繁体   English

Node.js在条件语句中调度函数

[英]Node.js scheduling function in conditional statement

I'm working on a project on Node.js. 我正在开发Node.js上的一个项目。 I want to execute some conditional code portion after waiting for five minutes since the last code does. 我想在自上一个代码执行以来等待五分钟后执行一些条件代码部分。 I only need it to run once that way (not everyday or ...). 我只需要它一次运行(不是每天或......)。 The rest of the code will take over but when it ticks five minute, that will execute. 其余的代码将接管,但当它在5分钟后,将执行。 Can I accomplish this? 我可以做到这一点吗?

EDIT: The code from Abdennour TOUMI partially works. 编辑: Abdennour TOUMI的代码部分有效。 But his way of denoting the minute by the variable didn't work for me. 但他用变量表示分钟的方式并不适用于我。 So I made the following edit according to the example from the module's page. 所以我根据模块页面中的示例进行了以下编辑。

            var schedule = require('node-schedule');

            var AFTER_5_MIN=new Date(new Date(new Date().getTime() + 5*60000))
            var date = new Date(AFTER_5_MIN);
            var j = schedule.scheduleJob(date, function() {
                if(condition1){
                     // Runned once --> Thus, you need to cancel it
                     // code here, than code to run once   
                    j.cancel();
                }else{

                    //it will be repeated
                 }
            });

Your mistake is use 5 fields & the right is 6 fields . 你的错误是使用5个字段,右边是6个字段。

  • * 0 * * * * --> For each hour at the 0 minute of that hour. * 0 * * * * - >每小时0分钟。

To start after 5 minutes , you could calculate the minute of hour after 5 minutes : 要在5分钟后开始,您可以计算5分钟后的小时数:

     var schedule = require('node-schedule');


     var AFTER_5_MIN=new Date(new Date(new Date().getTime() + 5*60000)).getMinutes();   

     var j = schedule.scheduleJob(`* ${AFTER_5_MIN} * * * *`, function() {
                    if(condition1){
                         // Runned once --> Thus, you need to cancel it
                         // code here, than code to run once   
                        j.cancel();
                    }else{

                        //it will be repeated
                     }
                });

Is there any reason you can't use setTimeout() ? 你有什么理由不能使用setTimeout()吗?

const WAIT_TIME = (60 * 5) * 1000; //5 Minutes

var timer = setTimeout(function(){
  console.log('Cron job works!')
}, WAIT_TIME);

/*
 * If conditions change in this five minutes and you need to cancel executing
 * the callback above, you can clear the timer
 * clearTimeout(timer);
 */

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

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