To schedule tasks in JavaScript, the setTimeout()
and setInterval()
functions are used to run code at specific times in the future (more information available here). With setTimeout()
, the code will execute once after a specified time interval. The setInterval()
function will repeatedly execute the code at the specified interval.
If you have a server running continuously, simply using setInterval()
is sufficient.
setInterval(myFunction, 1000 * 60 * 60 * 24);
This line of code will call the function myFunction
every 24 hours.
In addition to these basic functions, there are more advanced scheduling tools such as those found in packages like node-schedule on NPM. These tools offer features like complex scheduling patterns (e.g., running every other day and twice on Mondays) and persistence across server restarts.
For instance, I use a setInterval()
in my home automation server running on a Raspberry Pi to handle log management tasks once a day.