| 1 |
/* |
| 2 |
* Copyright (c) 2016-present, RxJava Contributors. |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in |
| 5 |
* compliance with the License. You may obtain a copy of the License at |
| 6 |
* |
| 7 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
* |
| 9 |
* Unless required by applicable law or agreed to in writing, software distributed under the License is |
| 10 |
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See |
| 11 |
* the License for the specific language governing permissions and limitations under the License. |
| 12 |
*/ |
| 13 |
|
| 14 |
package io.reactivex.rxjava3.core; |
| 15 |
|
| 16 |
import java.util.Objects; |
| 17 |
import java.util.concurrent.TimeUnit; |
| 18 |
|
| 19 |
import io.reactivex.rxjava3.annotations.*; |
| 20 |
import io.reactivex.rxjava3.disposables.Disposable; |
| 21 |
import io.reactivex.rxjava3.functions.Function; |
| 22 |
import io.reactivex.rxjava3.internal.disposables.*; |
| 23 |
import io.reactivex.rxjava3.internal.schedulers.*; |
| 24 |
import io.reactivex.rxjava3.plugins.RxJavaPlugins; |
| 25 |
import io.reactivex.rxjava3.schedulers.SchedulerRunnableIntrospection; |
| 26 |
|
| 27 |
/** |
| 28 |
* A {@code Scheduler} is an object that specifies an API for scheduling |
| 29 |
* units of work provided in the form of {@link Runnable}s to be |
| 30 |
* executed without delay (effectively as soon as possible), after a specified time delay or periodically |
| 31 |
* and represents an abstraction over an asynchronous boundary that ensures |
| 32 |
* these units of work get executed by some underlying task-execution scheme |
| 33 |
* (such as custom Threads, event loop, {@link java.util.concurrent.Executor Executor} or Actor system) |
| 34 |
* with some uniform properties and guarantees regardless of the particular underlying |
| 35 |
* scheme. |
| 36 |
* <p> |
| 37 |
* You can get various standard, RxJava-specific instances of this class via |
| 38 |
* the static methods of the {@link io.reactivex.rxjava3.schedulers.Schedulers} utility class. |
| 39 |
* <p> |
| 40 |
* The so-called {@link Worker}s of a {@code Scheduler} can be created via the {@link #createWorker()} method which allow the scheduling |
| 41 |
* of multiple {@link Runnable} tasks in an isolated manner. {@code Runnable} tasks scheduled on a {@code Worker} are guaranteed to be |
| 42 |
* executed sequentially and in a non-overlapping fashion. Non-delayed {@code Runnable} tasks are guaranteed to execute in a |
| 43 |
* First-In-First-Out order but their execution may be interleaved with delayed tasks. |
| 44 |
* In addition, outstanding or running tasks can be cancelled together via |
| 45 |
* {@link Worker#dispose()} without affecting any other {@code Worker} instances of the same {@code Scheduler}. |
| 46 |
* <p> |
| 47 |
* Implementations of the {@link #scheduleDirect} and {@link Worker#schedule} methods are encouraged to call the {@link io.reactivex.rxjava3.plugins.RxJavaPlugins#onSchedule(Runnable)} |
| 48 |
* method to allow a scheduler hook to manipulate (wrap or replace) the original {@code Runnable} task before it is submitted to the |
| 49 |
* underlying task-execution scheme. |
| 50 |
* <p> |
| 51 |
* The default implementations of the {@code scheduleDirect} methods provided by this abstract class |
| 52 |
* delegate to the respective {@code schedule} methods in the {@link Worker} instance created via {@link #createWorker()} |
| 53 |
* for each individual {@link Runnable} task submitted. Implementors of this class are encouraged to provide |
| 54 |
* a more efficient direct scheduling implementation to avoid the time and memory overhead of creating such {@code Worker}s |
| 55 |
* for every task. |
| 56 |
* This delegation is done via special wrapper instances around the original {@code Runnable} before calling the respective |
| 57 |
* {@code Worker.schedule} method. Note that this can lead to multiple {@code RxJavaPlugins.onSchedule} calls and potentially |
| 58 |
* multiple hooks applied. Therefore, the default implementations of {@code scheduleDirect} (and the {@link Worker#schedulePeriodically(Runnable, long, long, TimeUnit)}) |
| 59 |
* wrap the incoming {@code Runnable} into a class that implements the {@link io.reactivex.rxjava3.schedulers.SchedulerRunnableIntrospection} |
| 60 |
* interface which can grant access to the original or hooked {@code Runnable}, thus, a repeated {@code RxJavaPlugins.onSchedule} |
| 61 |
* can detect the earlier hook and not apply a new one over again. |
| 62 |
* <p> |
| 63 |
* The default implementation of {@link #now(TimeUnit)} and {@link Worker#now(TimeUnit)} methods to return current {@link System#currentTimeMillis()} |
| 64 |
* value in the desired time unit, unless {@code rx3.scheduler.use-nanotime} (boolean) is set. When the property is set to |
| 65 |
* {@code true}, the method uses {@link System#nanoTime()} as its basis instead. Custom {@code Scheduler} implementations can override this |
| 66 |
* to provide specialized time accounting (such as virtual time to be advanced programmatically). |
| 67 |
* Note that operators requiring a {@code Scheduler} may rely on either of the {@code now()} calls provided by |
| 68 |
* {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically |
| 69 |
* consistent source of the current time. |
| 70 |
* <p> |
| 71 |
* The default implementation of the {@link Worker#schedulePeriodically(Runnable, long, long, TimeUnit)} method uses |
| 72 |
* the {@link Worker#schedule(Runnable, long, TimeUnit)} for scheduling the {@code Runnable} task periodically. |
| 73 |
* The algorithm calculates the next absolute time when the task should run again and schedules this execution |
| 74 |
* based on the relative time between it and {@link Worker#now(TimeUnit)}. However, drifts or changes in the |
| 75 |
* system clock could affect this calculation either by scheduling subsequent runs too frequently or too far apart. |
| 76 |
* Therefore, the default implementation uses the {@link #clockDriftTolerance()} value (set via |
| 77 |
* {@code rx3.scheduler.drift-tolerance} and {@code rx3.scheduler.drift-tolerance-unit}) to detect a |
| 78 |
* drift in {@link Worker#now(TimeUnit)} and re-adjust the absolute/relative time calculation accordingly. |
| 79 |
* <p> |
| 80 |
* The default implementations of {@link #start()} and {@link #shutdown()} do nothing and should be overridden if the |
| 81 |
* underlying task-execution scheme supports stopping and restarting itself. |
| 82 |
* <p> |
| 83 |
* If the {@code Scheduler} is shut down or a {@code Worker} is disposed, the {@code schedule} methods |
| 84 |
* should return the {@link Disposable#disposed()} singleton instance indicating the shut down/disposed |
| 85 |
* state to the caller. Since the shutdown or dispose can happen from any thread, the {@code schedule} implementations |
| 86 |
* should make best effort to cancel tasks immediately after those tasks have been submitted to the |
| 87 |
* underlying task-execution scheme if the shutdown/dispose was detected after this submission. |
| 88 |
* <p> |
| 89 |
* All methods on the {@code Scheduler} and {@code Worker} classes should be thread safe. |
| 90 |
*/ |
| 91 |
public abstract class Scheduler { |
| 92 |
/** |
| 93 |
* Value representing whether to use {@link System#nanoTime()}, or default as clock for {@link #now(TimeUnit)} |
| 94 |
* and {@link Scheduler.Worker#now(TimeUnit)}. |
| 95 |
* <p> |
| 96 |
* Associated system parameter: |
| 97 |
* <ul> |
| 98 |
* <li>{@code rx3.scheduler.use-nanotime}, boolean, default {@code false} |
| 99 |
* </ul> |
| 100 |
*/ |
| 101 |
static boolean IS_DRIFT_USE_NANOTIME = Boolean.getBoolean("rx3.scheduler.use-nanotime"); |
| 102 |
|
| 103 |
/** |
| 104 |
* Returns the current clock time depending on state of {@link Scheduler#IS_DRIFT_USE_NANOTIME} in given {@code unit} |
| 105 |
* <p> |
| 106 |
* By default {@link System#currentTimeMillis()} will be used as the clock. When the property is set |
| 107 |
* {@link System#nanoTime()} will be used. |
| 108 |
* <p> |
| 109 |
* @param unit the time unit |
| 110 |
* @return the 'current time' in given unit |
| 111 |
* @throws NullPointerException if {@code unit} is {@code null} |
| 112 |
*/ |
| 113 |
static long computeNow(TimeUnit unit) { |
| 114 |
if (!IS_DRIFT_USE_NANOTIME) { |
| 115 |
return unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS); |
| 116 |
} |
| 117 |
return unit.convert(System.nanoTime(), TimeUnit.NANOSECONDS); |
| 118 |
} |
| 119 |
|
| 120 |
/** |
| 121 |
* The tolerance for a clock drift in nanoseconds where the periodic scheduler will rebase. |
| 122 |
* <p> |
| 123 |
* Associated system parameters: |
| 124 |
* <ul> |
| 125 |
* <li>{@code rx3.scheduler.drift-tolerance}, long, default {@code 15}</li> |
| 126 |
* <li>{@code rx3.scheduler.drift-tolerance-unit}, string, default {@code minutes}, |
| 127 |
* supports {@code seconds} and {@code milliseconds}. |
| 128 |
* </ul> |
| 129 |
*/ |
| 130 |
static final long CLOCK_DRIFT_TOLERANCE_NANOSECONDS = |
| 131 |
computeClockDrift( |
| 132 |
Long.getLong("rx3.scheduler.drift-tolerance", 15), |
| 133 |
System.getProperty("rx3.scheduler.drift-tolerance-unit", "minutes") |
| 134 |
); |
| 135 |
|
| 136 |
/** |
| 137 |
* Returns the clock drift tolerance in nanoseconds based on the input selection. |
| 138 |
* @param time the time value |
| 139 |
* @param timeUnit the time unit string |
| 140 |
* @return the time amount in nanoseconds |
| 141 |
*/ |
| 142 |
static long computeClockDrift(long time, String timeUnit) { |
| 143 |
if ("seconds".equalsIgnoreCase(timeUnit)) { |
| 144 |
return TimeUnit.SECONDS.toNanos(time); |
| 145 |
} else if ("milliseconds".equalsIgnoreCase(timeUnit)) { |
| 146 |
return TimeUnit.MILLISECONDS.toNanos(time); |
| 147 |
} |
| 148 |
return TimeUnit.MINUTES.toNanos(time); |
| 149 |
} |
| 150 |
|
| 151 |
/** |
| 152 |
* Returns the clock drift tolerance in nanoseconds. |
| 153 |
* <p>Related system properties: |
| 154 |
* <ul> |
| 155 |
* <li>{@code rx3.scheduler.drift-tolerance}, long, default {@code 15}</li> |
| 156 |
* <li>{@code rx3.scheduler.drift-tolerance-unit}, string, default {@code minutes}, |
| 157 |
* supports {@code seconds} and {@code milliseconds}. |
| 158 |
* </ul> |
| 159 |
* @return the tolerance in nanoseconds |
| 160 |
* @since 2.0 |
| 161 |
*/ |
| 162 |
public static long clockDriftTolerance() { |
| 163 |
return CLOCK_DRIFT_TOLERANCE_NANOSECONDS; |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* Retrieves or creates a new {@link Scheduler.Worker} that represents sequential execution of actions. |
| 168 |
* <p> |
| 169 |
* When work is completed, the {@code Worker} instance should be released |
| 170 |
* by calling {@link Scheduler.Worker#dispose()} to avoid potential resource leaks in the |
| 171 |
* underlying task-execution scheme. |
| 172 |
* <p> |
| 173 |
* Work on a {@link Scheduler.Worker} is guaranteed to be sequential and non-overlapping. |
| 174 |
* |
| 175 |
* @return a Worker representing a serial queue of actions to be executed |
| 176 |
*/ |
| 177 |
@NonNull |
| 178 |
public abstract Worker createWorker(); |
| 179 |
|
| 180 |
/** |
| 181 |
* Returns the 'current time' of the Scheduler in the specified time unit. |
| 182 |
* @param unit the time unit |
| 183 |
* @return the 'current time' |
| 184 |
* @throws NullPointerException if {@code unit} is {@code null} |
| 185 |
* @since 2.0 |
| 186 |
*/ |
| 187 |
public long now(@NonNull TimeUnit unit) { |
| 188 |
return computeNow(unit); |
| 189 |
} |
| 190 |
|
| 191 |
/** |
| 192 |
* Allows the Scheduler instance to start threads |
| 193 |
* and accept tasks on them. |
| 194 |
* <p> |
| 195 |
* Implementations should make sure the call is idempotent, thread-safe and |
| 196 |
* should not throw any {@code RuntimeException} if it doesn't support this |
| 197 |
* functionality. |
| 198 |
* |
| 199 |
* @since 2.0 |
| 200 |
*/ |
| 201 |
public void start() { |
| 202 |
|
| 203 |
} |
| 204 |
|
| 205 |
/** |
| 206 |
* Instructs the Scheduler instance to stop threads, |
| 207 |
* stop accepting tasks on any outstanding {@link Worker} instances |
| 208 |
* and clean up any associated resources with this Scheduler. |
| 209 |
* <p> |
| 210 |
* Implementations should make sure the call is idempotent, thread-safe and |
| 211 |
* should not throw any {@code RuntimeException} if it doesn't support this |
| 212 |
* functionality. |
| 213 |
* @since 2.0 |
| 214 |
*/ |
| 215 |
public void shutdown() { |
| 216 |
|
| 217 |
} |
| 218 |
|
| 219 |
/** |
| 220 |
* Schedules the given task on this Scheduler without any time delay. |
| 221 |
* |
| 222 |
* <p> |
| 223 |
* This method is safe to be called from multiple threads but there are no |
| 224 |
* ordering or non-overlapping guarantees between tasks. |
| 225 |
* |
| 226 |
* @param run the task to execute |
| 227 |
* |
| 228 |
* @return the Disposable instance that let's one cancel this particular task. |
| 229 |
* @throws NullPointerException if {@code run} is {@code null} |
| 230 |
* @since 2.0 |
| 231 |
*/ |
| 232 |
@NonNull |
| 233 |
public Disposable scheduleDirect(@NonNull Runnable run) { |
| 234 |
return scheduleDirect(run, 0L, TimeUnit.NANOSECONDS); |
| 235 |
} |
| 236 |
|
| 237 |
/** |
| 238 |
* Schedules the execution of the given task with the given time delay. |
| 239 |
* |
| 240 |
* <p> |
| 241 |
* This method is safe to be called from multiple threads but there are no |
| 242 |
* ordering guarantees between tasks. |
| 243 |
* |
| 244 |
* @param run the task to schedule |
| 245 |
* @param delay the delay amount, non-positive values indicate non-delayed scheduling |
| 246 |
* @param unit the unit of measure of the delay amount |
| 247 |
* @return the Disposable that let's one cancel this particular delayed task. |
| 248 |
* @throws NullPointerException if {@code run} or {@code unit} is {@code null} |
| 249 |
* @since 2.0 |
| 250 |
*/ |
| 251 |
@NonNull |
| 252 |
public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) { |
| 253 |
final Worker w = createWorker(); |
| 254 |
|
| 255 |
final Runnable decoratedRun = RxJavaPlugins.onSchedule(run); |
| 256 |
|
| 257 |
DisposeTask task = new DisposeTask(decoratedRun, w); |
| 258 |
|
| 259 |
w.schedule(task, delay, unit); |
| 260 |
|
| 261 |
return task; |
| 262 |
} |
| 263 |
|
| 264 |
/** |
| 265 |
* Schedules a periodic execution of the given task with the given initial time delay and repeat period. |
| 266 |
* |
| 267 |
* <p> |
| 268 |
* This method is safe to be called from multiple threads but there are no |
| 269 |
* ordering guarantees between tasks. |
| 270 |
* |
| 271 |
* <p> |
| 272 |
* The periodic execution is at a fixed rate, that is, the first execution will be after the |
| 273 |
* {@code initialDelay}, the second after {@code initialDelay + period}, the third after |
| 274 |
* {@code initialDelay + 2 * period}, and so on. |
| 275 |
* |
| 276 |
* @param run the task to schedule |
| 277 |
* @param initialDelay the initial delay amount, non-positive values indicate non-delayed scheduling |
| 278 |
* @param period the period at which the task should be re-executed |
| 279 |
* @param unit the unit of measure of the delay amount |
| 280 |
* @return the Disposable that let's one cancel this particular delayed task. |
| 281 |
* @throws NullPointerException if {@code run} or {@code unit} is {@code null} |
| 282 |
* @since 2.0 |
| 283 |
*/ |
| 284 |
@NonNull |
| 285 |
public Disposable schedulePeriodicallyDirect(@NonNull Runnable run, long initialDelay, long period, @NonNull TimeUnit unit) { |
| 286 |
final Worker w = createWorker(); |
| 287 |
|
| 288 |
final Runnable decoratedRun = RxJavaPlugins.onSchedule(run); |
| 289 |
|
| 290 |
PeriodicDirectTask periodicTask = new PeriodicDirectTask(decoratedRun, w); |
| 291 |
|
| 292 |
Disposable d = w.schedulePeriodically(periodicTask, initialDelay, period, unit); |
| 293 |
if (d == EmptyDisposable.INSTANCE) { |
| 294 |
return d; |
| 295 |
} |
| 296 |
|
| 297 |
return periodicTask; |
| 298 |
} |
| 299 |
|
| 300 |
/** |
| 301 |
* Allows the use of operators for controlling the timing around when |
| 302 |
* actions scheduled on workers are actually done. This makes it possible to |
| 303 |
* layer additional behavior on this {@link Scheduler}. The only parameter |
| 304 |
* is a function that flattens an {@link Flowable} of {@link Flowable} |
| 305 |
* of {@link Completable}s into just one {@link Completable}. There must be |
| 306 |
* a chain of operators connecting the returned value to the source |
| 307 |
* {@link Flowable} otherwise any work scheduled on the returned |
| 308 |
* {@link Scheduler} will not be executed. |
| 309 |
* <p> |
| 310 |
* When {@link Scheduler#createWorker()} is invoked a {@link Flowable} of |
| 311 |
* {@link Completable}s is onNext'd to the combinator to be flattened. If |
| 312 |
* the inner {@link Flowable} is not immediately subscribed to an calls to |
| 313 |
* {@link Worker#schedule} are buffered. Once the {@link Flowable} is |
| 314 |
* subscribed to actions are then onNext'd as {@link Completable}s. |
| 315 |
* <p> |
| 316 |
* Finally the actions scheduled on the parent {@link Scheduler} when the |
| 317 |
* inner most {@link Completable}s are subscribed to. |
| 318 |
* <p> |
| 319 |
* When the {@link Worker} is unsubscribed the {@link Completable} emits an |
| 320 |
* onComplete and triggers any behavior in the flattening operator. The |
| 321 |
* {@link Flowable} and all {@link Completable}s give to the flattening |
| 322 |
* function never onError. |
| 323 |
* <p> |
| 324 |
* Limit the amount concurrency two at a time without creating a new fix |
| 325 |
* size thread pool: |
| 326 |
* |
| 327 |
* <pre> |
| 328 |
* Scheduler limitScheduler = Schedulers.computation().when(workers -> { |
| 329 |
* // use merge max concurrent to limit the number of concurrent |
| 330 |
* // callbacks two at a time |
| 331 |
* return Completable.merge(Flowable.merge(workers), 2); |
| 332 |
* }); |
| 333 |
* </pre> |
| 334 |
* <p> |
| 335 |
* This is a slightly different way to limit the concurrency but it has some |
| 336 |
* interesting benefits and drawbacks to the method above. It works by |
| 337 |
* limited the number of concurrent {@link Worker}s rather than individual |
| 338 |
* actions. Generally each {@link Flowable} uses its own {@link Worker}. |
| 339 |
* This means that this will essentially limit the number of concurrent |
| 340 |
* subscribes. The danger comes from using operators like |
| 341 |
* {@link Flowable#zip(org.reactivestreams.Publisher, org.reactivestreams.Publisher, io.reactivex.rxjava3.functions.BiFunction)} where |
| 342 |
* subscribing to the first {@link Flowable} could deadlock the |
| 343 |
* subscription to the second. |
| 344 |
* |
| 345 |
* <pre> |
| 346 |
* Scheduler limitScheduler = Schedulers.computation().when(workers -> { |
| 347 |
* // use merge max concurrent to limit the number of concurrent |
| 348 |
* // Flowables two at a time |
| 349 |
* return Completable.merge(Flowable.merge(workers, 2)); |
| 350 |
* }); |
| 351 |
* </pre> |
| 352 |
* |
| 353 |
* Slowing down the rate to no more than than 1 a second. This suffers from |
| 354 |
* the same problem as the one above I could find an {@link Flowable} |
| 355 |
* operator that limits the rate without dropping the values (aka leaky |
| 356 |
* bucket algorithm). |
| 357 |
* |
| 358 |
* <pre> |
| 359 |
* Scheduler slowScheduler = Schedulers.computation().when(workers -> { |
| 360 |
* // use concatenate to make each worker happen one at a time. |
| 361 |
* return Completable.concat(workers.map(actions -> { |
| 362 |
* // delay the starting of the next worker by 1 second. |
| 363 |
* return Completable.merge(actions.delaySubscription(1, TimeUnit.SECONDS)); |
| 364 |
* })); |
| 365 |
* }); |
| 366 |
* </pre> |
| 367 |
* |
| 368 |
* <p>History: 2.0.1 - experimental |
| 369 |
* @param <S> a Scheduler and a Subscription |
| 370 |
* @param combine the function that takes a two-level nested Flowable sequence of a Completable and returns |
| 371 |
* the Completable that will be subscribed to and should trigger the execution of the scheduled Actions. |
| 372 |
* @return the Scheduler with the customized execution behavior |
| 373 |
* @throws NullPointerException if {@code combine} is {@code null} |
| 374 |
* @since 2.1 |
| 375 |
*/ |
| 376 |
@SuppressWarnings("unchecked") |
| 377 |
@NonNull |
| 378 |
public <S extends Scheduler & Disposable> S when(@NonNull Function<Flowable<Flowable<Completable>>, Completable> combine) { |
| 379 |
Objects.requireNonNull(combine, "combine is null"); |
| 380 |
return (S) new SchedulerWhen(combine, this); |
| 381 |
} |
| 382 |
|
| 383 |
/** |
| 384 |
* Represents an isolated, sequential worker of a parent Scheduler for executing {@code Runnable} tasks on |
| 385 |
* an underlying task-execution scheme (such as custom Threads, event loop, {@link java.util.concurrent.Executor Executor} or Actor system). |
| 386 |
* <p> |
| 387 |
* Disposing the {@link Worker} should cancel all outstanding work and allows resource cleanup. |
| 388 |
* <p> |
| 389 |
* The default implementations of {@link #schedule(Runnable)} and {@link #schedulePeriodically(Runnable, long, long, TimeUnit)} |
| 390 |
* delegate to the abstract {@link #schedule(Runnable, long, TimeUnit)} method. Its implementation is encouraged to |
| 391 |
* track the individual {@code Runnable} tasks while they are waiting to be executed (with or without delay) so that |
| 392 |
* {@link #dispose()} can prevent their execution or potentially interrupt them if they are currently running. |
| 393 |
* <p> |
| 394 |
* The default implementation of the {@link #now(TimeUnit)} method returns current {@link System#currentTimeMillis()} |
| 395 |
* value in the desired time unit, unless {@code rx3.scheduler.use-nanotime} (boolean) is set. When the property is set to |
| 396 |
* {@code true}, the method uses {@link System#nanoTime()} as its basis instead. Custom {@code Worker} implementations can override this |
| 397 |
* to provide specialized time accounting (such as virtual time to be advanced programmatically). |
| 398 |
* Note that operators requiring a scheduler may rely on either of the {@code now()} calls provided by |
| 399 |
* {@code Scheduler} or {@code Worker} respectively, therefore, it is recommended they represent a logically |
| 400 |
* consistent source of the current time. |
| 401 |
* <p> |
| 402 |
* The default implementation of the {@link #schedulePeriodically(Runnable, long, long, TimeUnit)} method uses |
| 403 |
* the {@link #schedule(Runnable, long, TimeUnit)} for scheduling the {@code Runnable} task periodically. |
| 404 |
* The algorithm calculates the next absolute time when the task should run again and schedules this execution |
| 405 |
* based on the relative time between it and {@link #now(TimeUnit)}. However, drifts or changes in the |
| 406 |
* system clock would affect this calculation either by scheduling subsequent runs too frequently or too far apart. |
| 407 |
* Therefore, the default implementation uses the {@link #clockDriftTolerance()} value (set via |
| 408 |
* {@code rx3.scheduler.drift-tolerance} and {@code rx3.scheduler.drift-tolerance-unit}) to detect a drift in {@link #now(TimeUnit)} and |
| 409 |
* re-adjust the absolute/relative time calculation accordingly. |
| 410 |
* <p> |
| 411 |
* If the {@code Worker} is disposed, the {@code schedule} methods |
| 412 |
* should return the {@link Disposable#disposed()} singleton instance indicating the disposed |
| 413 |
* state to the caller. Since the {@link #dispose()} call can happen on any thread, the {@code schedule} implementations |
| 414 |
* should make best effort to cancel tasks immediately after those tasks have been submitted to the |
| 415 |
* underlying task-execution scheme if the dispose was detected after this submission. |
| 416 |
* <p> |
| 417 |
* All methods on the {@code Worker} class should be thread safe. |
| 418 |
*/ |
| 419 |
public abstract static class Worker implements Disposable { |
| 420 |
/** |
| 421 |
* Schedules a Runnable for execution without any time delay. |
| 422 |
* |
| 423 |
* <p>The default implementation delegates to {@link #schedule(Runnable, long, TimeUnit)}. |
| 424 |
* |
| 425 |
* @param run |
| 426 |
* Runnable to schedule |
| 427 |
* @return a Disposable to be able to unsubscribe the action (cancel it if not executed) |
| 428 |
* @throws NullPointerException if {@code run} is {@code null} |
| 429 |
*/ |
| 430 |
@NonNull |
| 431 |
public Disposable schedule(@NonNull Runnable run) { |
| 432 |
return schedule(run, 0L, TimeUnit.NANOSECONDS); |
| 433 |
} |
| 434 |
|
| 435 |
/** |
| 436 |
* Schedules an Runnable for execution at some point in the future specified by a time delay |
| 437 |
* relative to the current time. |
| 438 |
* <p> |
| 439 |
* Note to implementors: non-positive {@code delayTime} should be regarded as non-delayed schedule, i.e., |
| 440 |
* as if the {@link #schedule(Runnable)} was called. |
| 441 |
* |
| 442 |
* @param run |
| 443 |
* the Runnable to schedule |
| 444 |
* @param delay |
| 445 |
* time to "wait" before executing the action; non-positive values indicate an non-delayed |
| 446 |
* schedule |
| 447 |
* @param unit |
| 448 |
* the time unit of {@code delayTime} |
| 449 |
* @return a Disposable to be able to unsubscribe the action (cancel it if not executed) |
| 450 |
* @throws NullPointerException if {@code run} or {@code unit} is {@code null} |
| 451 |
*/ |
| 452 |
@NonNull |
| 453 |
public abstract Disposable schedule(@NonNull Runnable run, long delay, @NonNull TimeUnit unit); |
| 454 |
|
| 455 |
/** |
| 456 |
* Schedules a periodic execution of the given task with the given initial time delay and repeat period. |
| 457 |
* <p> |
| 458 |
* The default implementation schedules and reschedules the {@code Runnable} task via the |
| 459 |
* {@link #schedule(Runnable, long, TimeUnit)} |
| 460 |
* method over and over and at a fixed rate, that is, the first execution will be after the |
| 461 |
* {@code initialDelay}, the second after {@code initialDelay + period}, the third after |
| 462 |
* {@code initialDelay + 2 * period}, and so on. |
| 463 |
* <p> |
| 464 |
* Note to implementors: non-positive {@code initialTime} and {@code period} should be regarded as |
| 465 |
* non-delayed scheduling of the first and any subsequent executions. |
| 466 |
* In addition, a more specific {@code Worker} implementation should override this method |
| 467 |
* if it can perform the periodic task execution with less overhead (such as by avoiding the |
| 468 |
* creation of the wrapper and tracker objects upon each periodic invocation of the |
| 469 |
* common {@link #schedule(Runnable, long, TimeUnit)} method). |
| 470 |
* |
| 471 |
* @param run |
| 472 |
* the Runnable to execute periodically |
| 473 |
* @param initialDelay |
| 474 |
* time to wait before executing the action for the first time; non-positive values indicate |
| 475 |
* an non-delayed schedule |
| 476 |
* @param period |
| 477 |
* the time interval to wait each time in between executing the action; non-positive values |
| 478 |
* indicate no delay between repeated schedules |
| 479 |
* @param unit |
| 480 |
* the time unit of {@code period} |
| 481 |
* @return a Disposable to be able to unsubscribe the action (cancel it if not executed) |
| 482 |
* @throws NullPointerException if {@code run} or {@code unit} is {@code null} |
| 483 |
*/ |
| 484 |
@NonNull |
| 485 |
public Disposable schedulePeriodically(@NonNull Runnable run, final long initialDelay, final long period, @NonNull final TimeUnit unit) { |
| 486 |
final SequentialDisposable first = new SequentialDisposable(); |
| 487 |
|
| 488 |
final SequentialDisposable sd = new SequentialDisposable(first); |
| 489 |
|
| 490 |
final Runnable decoratedRun = RxJavaPlugins.onSchedule(run); |
| 491 |
|
| 492 |
final long periodInNanoseconds = unit.toNanos(period); |
| 493 |
final long firstNowNanoseconds = now(TimeUnit.NANOSECONDS); |
| 494 |
final long firstStartInNanoseconds = firstNowNanoseconds + unit.toNanos(initialDelay); |
| 495 |
|
| 496 |
Disposable d = schedule(new PeriodicTask(firstStartInNanoseconds, decoratedRun, firstNowNanoseconds, sd, |
| 497 |
periodInNanoseconds), initialDelay, unit); |
| 498 |
|
| 499 |
if (d == EmptyDisposable.INSTANCE) { |
| 500 |
return d; |
| 501 |
} |
| 502 |
first.replace(d); |
| 503 |
|
| 504 |
return sd; |
| 505 |
} |
| 506 |
|
| 507 |
/** |
| 508 |
* Returns the 'current time' of the Worker in the specified time unit. |
| 509 |
* @param unit the time unit |
| 510 |
* @return the 'current time' |
| 511 |
* @throws NullPointerException if {@code unit} is {@code null} |
| 512 |
* @since 2.0 |
| 513 |
*/ |
| 514 |
public long now(@NonNull TimeUnit unit) { |
| 515 |
return computeNow(unit); |
| 516 |
} |
| 517 |
|
| 518 |
/** |
| 519 |
* Holds state and logic to calculate when the next delayed invocation |
| 520 |
* of this task has to happen (accounting for clock drifts). |
| 521 |
*/ |
| 522 |
final class PeriodicTask implements Runnable, SchedulerRunnableIntrospection { |
| 523 |
@NonNull |
| 524 |
final Runnable decoratedRun; |
| 525 |
@NonNull |
| 526 |
final SequentialDisposable sd; |
| 527 |
final long periodInNanoseconds; |
| 528 |
long count; |
| 529 |
long lastNowNanoseconds; |
| 530 |
long startInNanoseconds; |
| 531 |
|
| 532 |
PeriodicTask(long firstStartInNanoseconds, @NonNull Runnable decoratedRun, |
| 533 |
long firstNowNanoseconds, @NonNull SequentialDisposable sd, long periodInNanoseconds) { |
| 534 |
this.decoratedRun = decoratedRun; |
| 535 |
this.sd = sd; |
| 536 |
this.periodInNanoseconds = periodInNanoseconds; |
| 537 |
lastNowNanoseconds = firstNowNanoseconds; |
| 538 |
startInNanoseconds = firstStartInNanoseconds; |
| 539 |
} |
| 540 |
|
| 541 |
@Override |
| 542 |
public void run() { |
| 543 |
decoratedRun.run(); |
| 544 |
|
| 545 |
if (!sd.isDisposed()) { |
| 546 |
|
| 547 |
long nextTick; |
| 548 |
|
| 549 |
long nowNanoseconds = now(TimeUnit.NANOSECONDS); |
| 550 |
// If the clock moved in a direction quite a bit, rebase the repetition period |
| 551 |
if (nowNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS < lastNowNanoseconds |
| 552 |
|| nowNanoseconds >= lastNowNanoseconds + periodInNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS) { |
| 553 |
nextTick = nowNanoseconds + periodInNanoseconds; |
| 554 |
/* |
| 555 |
* Shift the start point back by the drift as if the whole thing |
| 556 |
* started count periods ago. |
| 557 |
*/ |
| 558 |
startInNanoseconds = nextTick - (periodInNanoseconds * (++count)); |
| 559 |
} else { |
| 560 |
nextTick = startInNanoseconds + (++count * periodInNanoseconds); |
| 561 |
} |
| 562 |
lastNowNanoseconds = nowNanoseconds; |
| 563 |
|
| 564 |
long delay = nextTick - nowNanoseconds; |
| 565 |
sd.replace(schedule(this, delay, TimeUnit.NANOSECONDS)); |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
@Override |
| 570 |
public Runnable getWrappedRunnable() { |
| 571 |
return this.decoratedRun; |
| 572 |
} |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
static final class PeriodicDirectTask |
| 577 |
implements Disposable, Runnable, SchedulerRunnableIntrospection { |
| 578 |
|
| 579 |
@NonNull |
| 580 |
final Runnable run; |
| 581 |
|
| 582 |
@NonNull |
| 583 |
final Worker worker; |
| 584 |
|
| 585 |
volatile boolean disposed; |
| 586 |
|
| 587 |
PeriodicDirectTask(@NonNull Runnable run, @NonNull Worker worker) { |
| 588 |
this.run = run; |
| 589 |
this.worker = worker; |
| 590 |
} |
| 591 |
|
| 592 |
@Override |
| 593 |
public void run() { |
| 594 |
if (!disposed) { |
| 595 |
try { |
| 596 |
run.run(); |
| 597 |
} catch (Throwable ex) { |
| 598 |
// Exceptions.throwIfFatal(ex); nowhere to go |
| 599 |
dispose(); |
| 600 |
RxJavaPlugins.onError(ex); |
| 601 |
throw ex; |
| 602 |
} |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
@Override |
| 607 |
public void dispose() { |
| 608 |
disposed = true; |
| 609 |
worker.dispose(); |
| 610 |
} |
| 611 |
|
| 612 |
@Override |
| 613 |
public boolean isDisposed() { |
| 614 |
return disposed; |
| 615 |
} |
| 616 |
|
| 617 |
@Override |
| 618 |
public Runnable getWrappedRunnable() { |
| 619 |
return run; |
| 620 |
} |
| 621 |
} |
| 622 |
|
| 623 |
static final class DisposeTask implements Disposable, Runnable, SchedulerRunnableIntrospection { |
| 624 |
|
| 625 |
@NonNull |
| 626 |
final Runnable decoratedRun; |
| 627 |
|
| 628 |
@NonNull |
| 629 |
final Worker w; |
| 630 |
|
| 631 |
@Nullable |
| 632 |
Thread runner; |
| 633 |
|
| 634 |
DisposeTask(@NonNull Runnable decoratedRun, @NonNull Worker w) { |
| 635 |
this.decoratedRun = decoratedRun; |
| 636 |
this.w = w; |
| 637 |
} |
| 638 |
|
| 639 |
@Override |
| 640 |
public void run() { |
| 641 |
runner = Thread.currentThread(); |
| 642 |
try { |
| 643 |
try { |
| 644 |
decoratedRun.run(); |
| 645 |
} catch (Throwable ex) { |
| 646 |
// Exceptions.throwIfFatal(e); nowhere to go |
| 647 |
RxJavaPlugins.onError(ex); |
| 648 |
throw ex; |
| 649 |
} |
| 650 |
} finally { |
| 651 |
dispose(); |
| 652 |
runner = null; |
| 653 |
} |
| 654 |
} |
| 655 |
|
| 656 |
@Override |
| 657 |
public void dispose() { |
| 658 |
if (runner == Thread.currentThread() && w instanceof NewThreadWorker) { |
| 659 |
((NewThreadWorker)w).shutdown(); |
| 660 |
} else { |
| 661 |
w.dispose(); |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
@Override |
| 666 |
public boolean isDisposed() { |
| 667 |
return w.isDisposed(); |
| 668 |
} |
| 669 |
|
| 670 |
@Override |
| 671 |
public Runnable getWrappedRunnable() { |
| 672 |
return this.decoratedRun; |
| 673 |
} |
| 674 |
} |
| 675 |
} |