I'm looking for a schedular/ cron for nodejs. But I need an important feature- if the jobs did not finish (when the time for it to start again arrived), I want it to not start/ delay the schedule. For example, I need to run a job every 5 minutes. The job started at 8:00, but finished only at 8:06. so I want the job of 8:05 to either wait until 8:06, or not to start at all, and wait for the next cycle at 8:10. Is there a package that does that? If not, what is the best way to implement this?
Asked
Active
Viewed 4,114 times
2 Answers
5
You can use the cron package. It allows you to start/stop the cronjob manually. Which means you can call these functions when your cronjob is finished.
const CronJob = require('cron').CronJob;
let job;
// The function you are running
const someFunction = () => {
job.stop();
doSomething(() => {
// When you are done
job.start();
})
};
// Create new cronjob
job = new CronJob({
cronTime: '00 00 1 * * *',
onTick: someFunction,
start: false,
timeZone: 'America/Los_Angeles'
});
// Auto start your cronjob
job.start();

Thomas Bormans
- 5,156
- 6
- 34
- 51
-
Tnanks! After looking at your solution I did something a bit different- at the end of the function, I call a timeout to this date plus 5 minutes. This works perfectly – netneta Jun 29 '17 at 11:27
2
You can implement it by yourself:
// The job has to have a method to inform about completion
function myJob(input, callback) {
setTimeout(callback, 10 * 60 * 1000); // It will complete in 10 minutes
}
// Scheduler
let jobIsRunning = false;
function scheduler() {
// Do nothing if job is still running
if (jobIsRunning) {
return;
}
// Mark the job as running
jobIsRunning = true;
myJob('some input', () => {
// Mark the job as completed
jobIsRunning = false;
});
}
setInterval(scheduler, 5 * 60 * 1000); // Run scheduler every 5 minutes

vsenko
- 1,129
- 8
- 20