Skip to content

Commit

Permalink
Merge pull request #1162 from kirkshoop/stableperiodic
Browse files Browse the repository at this point in the history
fix to remove drift from schedulePeriodic
  • Loading branch information
benjchristensen committed May 6, 2014
2 parents 3764051 + 67cae34 commit dded83c
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions rxjava-core/src/main/java/rx/Scheduler.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,16 @@ public abstract static class Worker implements Subscription {
*/
public Subscription schedulePeriodically(final Action0 action, long initialDelay, long period, TimeUnit unit) {
final long periodInNanos = unit.toNanos(period);
final long startInNanos = TimeUnit.MILLISECONDS.toNanos(now()) + unit.toNanos(initialDelay);

final Action0 recursiveAction = new Action0() {
long count = 0;
@Override
public void call() {
if (!isUnsubscribed()) {
long startedAt = now();
action.call();
long timeTakenByActionInNanos = TimeUnit.MILLISECONDS.toNanos(now() - startedAt);
schedule(this, periodInNanos - timeTakenByActionInNanos, TimeUnit.NANOSECONDS);
long nextTick = startInNanos + (++count * periodInNanos);
schedule(this, nextTick - TimeUnit.MILLISECONDS.toNanos(now()), TimeUnit.NANOSECONDS);
}
}
};
Expand Down

0 comments on commit dded83c

Please sign in to comment.