Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1.x: compensation for significant clock drifts in schedulePeriodically #3467

Merged
merged 1 commit into from
Dec 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions src/main/java/rx/Scheduler.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ public abstract class Scheduler {
* maintenance.
*/

/**
* The tolerance for a clock drift in nanoseconds where the periodic scheduler will rebase.
* <p>
* The associated system parameter, {@code rx.scheduler.drift-tolerance}, expects its value in minutes.
*/
static final long CLOCK_DRIFT_TOLERANCE_NANOS;
static {
CLOCK_DRIFT_TOLERANCE_NANOS = TimeUnit.MINUTES.toNanos(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason to put this into separate static block?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why, where is the other one?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implicitly using an initializer.

static final long CLOCK_DRIFT_TOLERANCE_NANOS =
    TimeUnit.MINUTES.toNanos(Long.getLong("rx.scheduler.drift-tolerance", 15));

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep, ^.

BTW, @akarnokd don't you think that minutes is not the best unit of time measurement in programming? I'd prefer millis, long seems enough for CLOCK_DRIFT_TOLERANCE, and anyway, you're converting it to nanos then so long is 100% enough for millis.

Also, 15 minutes seems too much for a default clock drift tolerance…

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't inline it in case more parameters are asked for within this PR.

It is a question what is a reasonable tolerance for detecting drifts. One could argue it should be the function of the drift direction and the length of the period instead:

  • if now moves backwards by any number, do the correction,
  • if now moves ahead more than 1.5 times the period, do the correction.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@akarnokd Is it your preference to create a separate factor rx.scheduler.drift-tolerance-backward and rx.scheduler.drift-tolerance-forward?

I think the tolerance setting would be more easily generalized as a percentage of the period but it would be slightly more difficult to grok (if that is ever actually a concern for users). I'm okay with converting this to a percentage value.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd leave it as it is now. I'm not sure about the percentage because what if the task itself is slow instead of a clock drift?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@akarnokd May you please allow to set CLOCK_DRIFT_TOLERANCE_NANOS in seconds/milliseconds? I have a code which controls player position to play short pieces (few seconds) of media and pause them when the position is reached. Such as player may have various playback issues (fast/slow playback, delay in initialization) i use Flowable.interval(50ms) to check its state/position periodically. However when system time synchronization occurs during playback flowable stops fire events until time become the same as it was before synchronization
Here how it looks in my log

14:21:43.273 z1 D PlaybackDurationControlCompletable.onTick: player position is unchanged, skipping check
14:21:37.727 z1 D some other event, time syncrhonization occurrs
// ... no onTick events for 6 seconds
14:21:43.372 z1 D PlaybackDurationControlCompletable: Initializing position 41769; elapsedTimerTime=5757 

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please post a separate issue about this case.

Long.getLong("rx.scheduler.drift-tolerance", 15));
}

/**
* Retrieves or creates a new {@link Scheduler.Worker} that represents serial execution of actions.
* <p>
Expand Down Expand Up @@ -109,17 +120,38 @@ 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 long firstNowNanos = TimeUnit.MILLISECONDS.toNanos(now());
final long firstStartInNanos = firstNowNanos + unit.toNanos(initialDelay);

final MultipleAssignmentSubscription mas = new MultipleAssignmentSubscription();
final Action0 recursiveAction = new Action0() {
long count = 0;
long count;
long lastNowNanos = firstNowNanos;
long startInNanos = firstStartInNanos;
@Override
public void call() {
if (!mas.isUnsubscribed()) {
action.call();
long nextTick = startInNanos + (++count * periodInNanos);
mas.set(schedule(this, nextTick - TimeUnit.MILLISECONDS.toNanos(now()), TimeUnit.NANOSECONDS));

long nextTick;

long nowNanos = TimeUnit.MILLISECONDS.toNanos(now());
// If the clock moved in a direction quite a bit, rebase the repetition period
if (nowNanos + CLOCK_DRIFT_TOLERANCE_NANOS < lastNowNanos
|| nowNanos >= lastNowNanos + periodInNanos + CLOCK_DRIFT_TOLERANCE_NANOS) {
nextTick = nowNanos + periodInNanos;
/*
* Shift the start point back by the drift as if the whole thing
* started count periods ago.
*/
startInNanos = nextTick - (periodInNanos * (++count));
} else {
nextTick = startInNanos + (++count * periodInNanos);
}
lastNowNanos = nowNanos;

long delay = nextTick - nowNanos;
mas.set(schedule(this, delay, TimeUnit.NANOSECONDS));
}
}
};
Expand Down
153 changes: 153 additions & 0 deletions src/test/java/rx/SchedulerWorkerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx;

import static org.junit.Assert.assertTrue;

import java.util.*;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import rx.functions.Action0;
import rx.schedulers.Schedulers;

public class SchedulerWorkerTest {

static final class CustomDriftScheduler extends Scheduler {
public volatile long drift;
@Override
public Worker createWorker() {
final Worker w = Schedulers.computation().createWorker();
return new Worker() {

@Override
public void unsubscribe() {
w.unsubscribe();
}

@Override
public boolean isUnsubscribed() {
return w.isUnsubscribed();
}

@Override
public Subscription schedule(Action0 action) {
return w.schedule(action);
}

@Override
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
return w.schedule(action, delayTime, unit);
}

@Override
public long now() {
return super.now() + drift;
}
};
}

@Override
public long now() {
return super.now() + drift;
}
}

@Test
public void testCurrentTimeDriftBackwards() throws Exception {
CustomDriftScheduler s = new CustomDriftScheduler();

Scheduler.Worker w = s.createWorker();

try {
final List<Long> times = new ArrayList<Long>();

Subscription d = w.schedulePeriodically(new Action0() {
@Override
public void call() {
times.add(System.currentTimeMillis());
}
}, 100, 100, TimeUnit.MILLISECONDS);

Thread.sleep(150);

s.drift = -1000 - TimeUnit.NANOSECONDS.toMillis(Scheduler.CLOCK_DRIFT_TOLERANCE_NANOS);

Thread.sleep(400);

d.unsubscribe();

Thread.sleep(150);

System.out.println("Runs: " + times.size());

for (int i = 0; i < times.size() - 1 ; i++) {
long diff = times.get(i + 1) - times.get(i);
System.out.println("Diff #" + i + ": " + diff);
assertTrue("" + i + ":" + diff, diff < 150 && diff > 50);
}

assertTrue("Too few invocations: " + times.size(), times.size() > 2);

} finally {
w.unsubscribe();
}

}

@Test
public void testCurrentTimeDriftForwards() throws Exception {
CustomDriftScheduler s = new CustomDriftScheduler();

Scheduler.Worker w = s.createWorker();

try {
final List<Long> times = new ArrayList<Long>();

Subscription d = w.schedulePeriodically(new Action0() {
@Override
public void call() {
times.add(System.currentTimeMillis());
}
}, 100, 100, TimeUnit.MILLISECONDS);

Thread.sleep(150);

s.drift = 1000 + TimeUnit.NANOSECONDS.toMillis(Scheduler.CLOCK_DRIFT_TOLERANCE_NANOS);

Thread.sleep(400);

d.unsubscribe();

Thread.sleep(150);

System.out.println("Runs: " + times.size());

assertTrue(times.size() > 2);

for (int i = 0; i < times.size() - 1 ; i++) {
long diff = times.get(i + 1) - times.get(i);
System.out.println("Diff #" + i + ": " + diff);
assertTrue("Diff out of range: " + diff, diff < 250 && diff > 50);
}

} finally {
w.unsubscribe();
}

}
}