There are many questions related to my question but none that I could find are for node js such as this one, in addition, I would like to know how to run a cron job at a random time within a period every period, for my particular use I would like to run a cron job at a random time within an hour every hour. For example the random time between 10:00-11:00 is 10:15 then the random time between 11:00-12:00 is 11:53, and so on.
Asked
Active
Viewed 434 times
1
-
Set your cron to 10:00 ans add random timeout. It's what is done in the answers to the question you linked – Konrad Nov 28 '22 at 08:28
-
1I've solved this but getting random delay(between the minimum(0) and maximum time(60*60 = 3600)) in the cron job's callback and sleeping for that random amount of seconds before proceeding with the callback. – MShakeG Nov 30 '22 at 15:29
1 Answers
0
function scraper() {
// do something here
}
// CronJob runs function every hour at minute 0 second 0
const scraperTimer = new CronJob('0 0 */1 * * *', function () {
// set random delay between 5(min) and 50(max) minutes
const delay = Math.floor(Math.random() * (3e6 - 300000) + 300000);
setTimeout(() => {
scraper();
}, delay);
console.log(`running scraper in ${delay / 60000} minutes`);
});
scraperTimer.Start()
It would be good to be cautious of scope when using Cron and timers, memory leaks can happen.