@Override public Disposable schedulePeriodically(Runnable task, long initialDelay, long period, TimeUnit unit) { final long periodInNanoseconds = unit.toNanos(period); final long firstNowNanoseconds = nanoTime; final long firstStartInNanoseconds = firstNowNanoseconds + unit.toNanos(initialDelay); PeriodicTask periodicTask = new PeriodicTask(firstStartInNanoseconds, task, firstNowNanoseconds, periodInNanoseconds); replace(periodicTask, schedule(periodicTask, initialDelay, unit)); return periodicTask; }
@Override public void run() { decoratedRun.run(); if (get() != CANCELLED && !shutdown) { long nextTick; long nowNanoseconds = nanoTime; // If the clock moved in a direction quite a bit, rebase the repetition period if (nowNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS < lastNowNanoseconds || nowNanoseconds >= lastNowNanoseconds + periodInNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS) { nextTick = nowNanoseconds + periodInNanoseconds; /* * Shift the start point back by the drift as if the whole thing * started count periods ago. */ startInNanoseconds = nextTick - (periodInNanoseconds * (++count)); } else { nextTick = startInNanoseconds + (++count * periodInNanoseconds); } lastNowNanoseconds = nowNanoseconds; long delay = nextTick - nowNanoseconds; replace(this, schedule(this, delay, TimeUnit.NANOSECONDS)); } }
@Override public Disposable schedulePeriodically(Runnable task, long initialDelay, long period, TimeUnit unit) { final long periodInNanoseconds = unit.toNanos(period); final long firstNowNanoseconds = nanoTime; final long firstStartInNanoseconds = firstNowNanoseconds + unit.toNanos(initialDelay); PeriodicTask periodicTask = new PeriodicTask(firstStartInNanoseconds, task, firstNowNanoseconds, periodInNanoseconds); replace(periodicTask, schedule(periodicTask, initialDelay, unit)); return periodicTask; }
@Override public void run() { decoratedRun.run(); if (get() != CANCELLED && !shutdown) { long nextTick; long nowNanoseconds = nanoTime; // If the clock moved in a direction quite a bit, rebase the repetition period if (nowNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS < lastNowNanoseconds || nowNanoseconds >= lastNowNanoseconds + periodInNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS) { nextTick = nowNanoseconds + periodInNanoseconds; /* * Shift the start point back by the drift as if the whole thing * started count periods ago. */ startInNanoseconds = nextTick - (periodInNanoseconds * (++count)); } else { nextTick = startInNanoseconds + (++count * periodInNanoseconds); } lastNowNanoseconds = nowNanoseconds; long delay = nextTick - nowNanoseconds; replace(this, schedule(this, delay, TimeUnit.NANOSECONDS)); } }