|
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<?>>(); |
| 31 | + private final TimeUnit tickTimeUnit; |
30 | 32 | private long passedTicks = 0; |
| 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 | + } |
31 | 47 |
|
32 | 48 | /** |
33 | 49 | * Runs time forwards by a given duration, executing any commands scheduled for |
@@ -219,7 +235,7 @@ public long getDelay(TimeUnit unit) { |
219 | 235 | if (delay == null) { |
220 | 236 | delay = ranAtTicks - passedTicks; |
221 | 237 | } |
222 | | - return unit.convert(delay, TimeUnit.MILLISECONDS); |
| 238 | + return unit.convert(delay, tickTimeUnit); |
223 | 239 | } |
224 | 240 |
|
225 | 241 | public int compareTo(Delayed o) { |
@@ -269,7 +285,7 @@ public void run() { |
269 | 285 | } |
270 | 286 |
|
271 | 287 | private long toTicks(long duration, TimeUnit timeUnit) { |
272 | | - return TimeUnit.MILLISECONDS.convert(duration, timeUnit); |
| 288 | + return tickTimeUnit.convert(duration, timeUnit); |
273 | 289 | } |
274 | 290 |
|
275 | 291 | private UnsupportedSynchronousOperationException blockingOperationsNotSupported() { |
|
0 commit comments