简体   繁体   中英

Node.js scheduling function in conditional statement

I'm working on a project on 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. Can I accomplish this?

EDIT: The code from Abdennour TOUMI partially works. 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 .

  • * 0 * * * * --> For each hour at the 0 minute of that hour.

To start after 5 minutes , you could calculate the minute of hour after 5 minutes :

     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() ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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