I can write a setInterval() function or use something like node-scheduler , but they don't offer a robust solution. I have to log the last execution time somewhere in a DB and when the server boots up I again have to do a setInteterval . This is to make sure the timing is not screwed up if the server reboots due to a deployment, failure etc..
So, my questions are:
The easiest way would be to use the default scheduler of the operating system you are on (for example cron on most *NIX) which triggers the task. Other than that, you might want to use forever or pm2 to get your node application started and then construct your own scheduler like this:
// todo: error management
// todo: improve architecture and patterns
const fs = require('fs');
// on startup, read last execution time
let lastExecTime = new Date(fs.readFileSync('lastExec.txt', { encoding: 'utf8' }));
// this is the scheduler which fires every minute
function customSchedule() {
const now = new Date();
// check if 3600000ms (=1h) have passed
if (now - lastExecTime > 1000 * 60 * 60) {
// run hourly task here
// remember last execution time
lastExecTime = now;
fs.writeFileSync('lastExec.txt', now.toString());
}
// fire the next time in 1min
setTimeout(customSchedule, 1000 * 60);
}
// start the scheduling
customSchedule();
It will fire every minute and check if an hour or more has passed since the last execution. If so, it will execute your hourly task. For the daily/weekly ones, I leave the implementation to you :)
As for hosted services, many PHP-hosters allow for cron schedules. As for nodejs hosters, you can just roll the above code :)
Best way to run some tasks periodicaly is to use CRONS or Celery.
There is nodeJs wrapper for Celery which you can use to create periodic tasks .
Even using CRON is also better option. NodeJs wrapper for cron
Peter Scheler
JS enthusiast
Some years ago I contributed to a package called "date-events".
This package is exactly build for your use case.
And yes, like Marco Alka said, you should combine it with something like "forever" or "pm2".