Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava: How to to execute a task every 5 seconds only if the last task finished

I'm using RxJava. I have to execute a specific task every 5 seconds. That works perfectly by using the "Observable.Interval" method. However, I also have the following constraint: A new task must not be executed if the last task didn't finished. In this case, the new task need to be executed only when the last one finished.

I can't figure out how to do this simply with RxJava.

All ideas would be really appreciated ^^

Thanks for reading.

like image 282
ayorosmage Avatar asked Dec 10 '16 14:12

ayorosmage


2 Answers

When you call interval a worker is selected that corresponds to a single thread from the given scheduler (default is computation):

Observable
    .interval(5, TimeUnit.SECONDS)
    .flatMap(n -> task());

or if nothing is returned by the task:

Observable
   .interval(5, TimeUnit.SECONDS)
   .doOnNext(n -> task());

This means that for every 5 seconds there will be a run but if the task takes 5 or more seconds then the tasks will be running continuously (but not concurrently).

If you want to ensure a gap between running tasks then you could skip tasks based on the time of the finish of the last task. I can flesh that out if you need it.

like image 91
Dave Moten Avatar answered Jan 03 '23 13:01

Dave Moten


Small fix to Dave Moten's answer: if need it to actually work - you should NOT forget to subscribe. You should do

   Observable
    .interval(5, TimeUnit.SECONDS)
    .doOnNext(n -> task())
    .subscribe()
like image 44
dkzm Avatar answered Jan 03 '23 14:01

dkzm