5

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?

jsalonen
  • 29,593
  • 15
  • 91
  • 109
Darren
  • 2,888
  • 1
  • 23
  • 34

1 Answers1

8

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

Community
  • 1
  • 1
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Is that true even if the callback is doing IO? I thought that setInterval would fire even if the previous invocation was still waiting for an IO callback? – Darren Dec 01 '11 at 21:49
  • Yes, it will fire again. But you can set a "lock" variable or something like that if you want to avoid simultaneous IO requests – hugomg Dec 01 '11 at 21:52
  • Thanks, that seems to be the closest equivalent. I was hoping there was a nicer way than checking a lock variable although it wouldn't be too hard to wrap the whole thing up into a function. – Darren Dec 02 '11 at 15:52
  • @Darren: Yes, I would highly recomend wraping this and hiding the lock variable. – hugomg Dec 02 '11 at 16:13