SchedulerImpl implements Scheduler { @Override public <T> ScheduledCompletableFuture<T> schedule(SchedulerRunnable runnable, TemporalAdjuster temporalAdjuster) { final ScheduledCompletableFutureRecurring<T> schedule = new ScheduledCompletableFutureRecurring<>(); schedule(schedule, runnable, temporalAdjuster); return schedule; }  @Override ScheduledCompletableFuture<Instant> after(Duration duration); @Override ScheduledCompletableFuture<T> after(Callable<T> callable, Duration duration); @Override ScheduledCompletableFuture<T> before(CompletableFuture<T> promise, Duration timeout); @Override ScheduledCompletableFuture<Instant> at(Instant instant); @Override ScheduledCompletableFuture<T> at(Callable<T> callable, Instant instant); @Override ScheduledCompletableFuture<T> schedule(SchedulerRunnable runnable, TemporalAdjuster temporalAdjuster);  }
@Test @Timeout(value = 1, unit = TimeUnit.SECONDS) public void testSchedule() throws InterruptedException { Semaphore s = new Semaphore(0); TestSchedulerTemporalAdjuster temporalAdjuster = new TestSchedulerTemporalAdjuster(); scheduler.schedule(s::release, temporalAdjuster); s.acquire(3); Thread.sleep(300); assertEquals(0, s.availablePermits(), "Scheduler should not have released more after done"); assertEquals(3, temporalAdjuster.getCount(), "Scheduler should have run 3 times"); }
@Test @Timeout(value = 1, unit = TimeUnit.SECONDS) public void testScheduleCancel() throws InterruptedException { Semaphore s = new Semaphore(0); TestSchedulerTemporalAdjuster temporalAdjuster = new TestSchedulerTemporalAdjuster(); ScheduledCompletableFuture<Void> schedule = scheduler.schedule(s::release, temporalAdjuster); s.acquire(1); Thread.sleep(50); schedule.cancel(true); Thread.sleep(300); assertEquals(0, s.availablePermits(), "Scheduler should not have released more after cancel"); assertEquals(1, temporalAdjuster.getCount(), "Scheduler should have run 1 time"); }
@Test @Timeout(value = 1, unit = TimeUnit.SECONDS) public void testScheduleException() throws InterruptedException { Semaphore s = new Semaphore(0); TestSchedulerTemporalAdjuster temporalAdjuster = new TestSchedulerTemporalAdjuster(); SchedulerRunnable runnable = () -> { throw new FileNotFoundException("testBeforeTimeoutException"); }; ScheduledCompletableFuture<Void> schedule = scheduler.schedule(runnable, temporalAdjuster); schedule.getPromise().exceptionally(e -> { if (e instanceof FileNotFoundException) { s.release(); } return null; }); s.acquire(1); Thread.sleep(300); assertEquals(0, s.availablePermits(), "Scheduler should not have released more after cancel"); assertEquals(0, temporalAdjuster.getCount(), "Scheduler should have run 0 time"); }