I have written a NodeJS app that calls an API and posts to an endpoint only on weekdays at a specific time.
I could setup a cron job to run the app at the specified time but I'd prefer to run it with node index.js
and have it run constantly, doing nothing until it's the right day and time and then going back to "sleep" until the following day.
How do I achieve that? I tried with a while loop:
while (true) {
myApp.run();
}
Obviously that didn't go too well.
What's the right way to do it? Should I rewrite my modules to use events, so that I emit one when it's time and there is a listener that reacts to it?
--edit: To be more specific, I would like it to run in a similar way to an app that has a webserver in it. When you start the app, it's running and waiting for connections; it doesn't exit when the request & connection end, it stays running waiting for more requests & connections.
--edit 2: The reason I'd rather not use a cron is because the days and time to run on are configurable in a config.json
file that the app parses. I'd rather avoid messing with cron
and just change the schedule by editing the config.json
file.
--edit 3: I'd like to code this myself and not use a module. My brain always hurts when trying to write an app that would run forever and I'd like to understand how it's done rather than using a module.
--edit 4: Here is what I ended up using:
function doStuff() {
// code to run
};
function run() {
setInterval(doStuff, 30000);
};
run();
So here is how I solved it, as @AJS suggested:
function myApp() {
while (!isItTimeYet) {
setInterval(myApp, 59000);
}
}
It was simpler than I thought and hopefully it doesn't leak memory.
--edit: This is wrong and leaks memory because each loop makes it one level deeper. This is the way:
function doStuff() {
// code to run
};
function run() {
setInterval(doStuff, 30000);
};
run();