unknown unknown - 4 months ago 11
Javascript Question

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. https://www.npmjs.com/package/node-schedule

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

var AFTER_5_MIN=new Date(new Date(new Date().getTime() + 1*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
}
});

Answer

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