What is the purpose of ScheduledFuture.get() method if is retrieved from the scheduleWithFixedDelay/scheduleAtFixedRate method
ScheduledFuture can be used to get time left before next task execution:
ScheduledFuture<?> f = Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("run");
}
}, 0, 10000, TimeUnit.MILLISECONDS);
Thread.sleep(1000);
System.out.println("Time left before next run " + f.getDelay(TimeUnit.MILLISECONDS));
prints
run
Time left before next run 8999
I tried this out with the following code:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
AtomicInteger count = new AtomicInteger(0);
Runnable task = () -> {
int currentCount = count.incrementAndGet();
System.out.println("Task #" + currentCount + " started");
if (currentCount == 2) {
System.out.println("Shutting down scheduler...");
scheduler.shutdown();
}
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
System.out.println("Task #" + currentCount + " finished");
};
System.out.println("Starting scheduler...");
ScheduledFuture<?> scheduledFuture = scheduler.scheduleWithFixedDelay(
task, 0, 2, TimeUnit.SECONDS);
System.out.println("Getting scheduled future...");
System.out.println(scheduledFuture.get());
System.out.println("End of code reached.");
Here is the output:
Exception in thread "main" java.util.concurrent.CancellationException
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:121)
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191)
at Rextester.main(source.java:33)
Starting scheduler...
Getting scheduled future...
Task #1 started
Task #1 finished
Task #2 started
Shutting down scheduler...
Task #2 finished
Online Rextester Demo: https://rextester.com/LYKN32123
Not sure how useful this is but it shows the get()
method throws a CancellationException
if the scheduler is shut down.