Skip to content

Commit dded83c

Browse files
Merge pull request #1162 from kirkshoop/stableperiodic
fix to remove drift from schedulePeriodic
2 parents 3764051 + 67cae34 commit dded83c

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

rxjava-core/src/main/java/rx/Scheduler.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,15 +99,16 @@ public abstract static class Worker implements Subscription {
9999
*/
100100
public Subscription schedulePeriodically(final Action0 action, long initialDelay, long period, TimeUnit unit) {
101101
final long periodInNanos = unit.toNanos(period);
102+
final long startInNanos = TimeUnit.MILLISECONDS.toNanos(now()) + unit.toNanos(initialDelay);
102103

103104
final Action0 recursiveAction = new Action0() {
105+
long count = 0;
104106
@Override
105107
public void call() {
106108
if (!isUnsubscribed()) {
107-
long startedAt = now();
108109
action.call();
109-
long timeTakenByActionInNanos = TimeUnit.MILLISECONDS.toNanos(now() - startedAt);
110-
schedule(this, periodInNanos - timeTakenByActionInNanos, TimeUnit.NANOSECONDS);
110+
long nextTick = startInNanos + (++count * periodInNanos);
111+
schedule(this, nextTick - TimeUnit.MILLISECONDS.toNanos(now()), TimeUnit.NANOSECONDS);
111112
}
112113
}
113114
};

0 commit comments

Comments
 (0)