Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling with a fixed delay in node.js

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?

like image 463
Darren Avatar asked Dec 01 '11 21:12

Darren


1 Answers

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

like image 123
hugomg Avatar answered Oct 10 '22 01:10

hugomg