I'm looking for a way to periodically perform a background activity where the execution time of the activity might exceed the polling interval.
In java terms I'd use Executor.scheduleWithFixedDelay. This ensures that subsequent invocations only get called once the running task has completed, so only one instance of the task is running at any given time and it will always wait for the desired interval before polling again.
Currently I need to remember to make each activity reschedule itself upon completion. Is there a node.js / javascript library that achieves the same thing?
If you just want a simple function running every couple of seconds you can use setInterval
.
setInterval
will schedule to call your callback at the regular interval specified. If your callback takes longer then that to finish the "delayed" call on wait is then run as soon as possible. If you take longer then two intervals to finish then it ignores the older "ticks" and keeps only the latest one.
var task_is_running = false;
setInterval(function(){
if(!task_is_running){
task_is_running = true;
do_something(42, function(result){
task_is_running = false;
});
}
}, time_interval_in_miliseconds);
For a good explanation of setInterval and a comparison with setTimeout see https://stackoverflow.com/a/731625/90511
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With