|
2 | 2 |
|
3 | 3 | import java.util.Collection;
|
4 | 4 | import java.util.List;
|
| 5 | +import java.util.Objects; |
5 | 6 | import java.util.concurrent.Callable;
|
6 | 7 | import java.util.concurrent.Delayed;
|
7 | 8 | import java.util.concurrent.ExecutionException;
|
|
27 | 28 | */
|
28 | 29 | public class DeterministicScheduler implements ScheduledExecutorService {
|
29 | 30 | private final DeltaQueue<ScheduledTask<?>> deltaQueue = new DeltaQueue<ScheduledTask<?>>();
|
30 |
| - |
| 31 | + |
| 32 | + private final TimeUnit tickTimeUnit; |
| 33 | + |
| 34 | + public DeterministicScheduler() { |
| 35 | + this(TimeUnit.MILLISECONDS); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * A {@link TimeUnit} may be provided for custom tick precision. This can be helpful when operating |
| 40 | + * with nanosecond or microsecond precision. |
| 41 | + * |
| 42 | + * @param tickTimeUnit Time unit to use for ticks. |
| 43 | + */ |
| 44 | + public DeterministicScheduler(TimeUnit tickTimeUnit) { |
| 45 | + this.tickTimeUnit = Objects.requireNonNull(tickTimeUnit, "TimeUnit is required"); |
| 46 | + } |
| 47 | + |
31 | 48 | /**
|
32 | 49 | * Runs time forwards by a given duration, executing any commands scheduled for
|
33 | 50 | * execution during that time period, and any background tasks spawned by the
|
@@ -210,7 +227,7 @@ public boolean repeats() {
|
210 | 227 | }
|
211 | 228 |
|
212 | 229 | public long getDelay(TimeUnit unit) {
|
213 |
| - return unit.convert(deltaQueue.delay(this), TimeUnit.MILLISECONDS); |
| 230 | + return unit.convert(deltaQueue.delay(this), tickTimeUnit); |
214 | 231 | }
|
215 | 232 |
|
216 | 233 | public int compareTo(Delayed o) {
|
@@ -258,7 +275,7 @@ public void run() {
|
258 | 275 | }
|
259 | 276 |
|
260 | 277 | private long toTicks(long duration, TimeUnit timeUnit) {
|
261 |
| - return TimeUnit.MILLISECONDS.convert(duration, timeUnit); |
| 278 | + return tickTimeUnit.convert(duration, timeUnit); |
262 | 279 | }
|
263 | 280 |
|
264 | 281 | private UnsupportedSynchronousOperationException blockingOperationsNotSupported() {
|
|
0 commit comments