56.14 Scheduling Tasks
The final area to be covered involves the use of ExecutorService to schedule task execution. This involves use of a ScheduledExecutorService instance on which the schedule() method needs to be called passing through the Runnable task to be executed together with a time delay. The schedule() call will return a ScheduledFuture instance which may be used to identify the remaining time before the task is due to start.
The following code, for example, schedules a task to run after a 30 second delay and accesses the remaining delay time:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
// Code to perform task here
};
ScheduledFuture<?> future = executor.schedule(task, 30, TimeUnit.SECONDS);
long delayRemaining = future.getDelay(TimeUnit.SECONDS);
Similarly, the ScheduledExecutorService may be used to execute a task repeatedly at regular intervals starting after an optional initial delay...