00:00

ScheduledFuture Interface in Java: Delays, Results and Cancellation

Last updated:

Every scheduling method of ScheduledExecutorService returns a ScheduledFuture. It is a Future that also knows how long remains until the task runs.

This tutorial shows what the interface inherits, how to read the remaining delay, how scheduled futures sort by time, and how to cancel them.

1. What Is ScheduledFuture?

ScheduledFuture<V> is an interface in java.util.concurrent, added in Java 5. It declares no methods of its own; it simply combines Delayed and Future<V>.

ScheduledFuture.java (JDK declaration)
public interface ScheduledFuture<V> extends Delayed, Future<V> {
}

From Delayed it gets getDelay(TimeUnit), and because Delayed extends Comparable<Delayed>, scheduled futures can be ordered by how soon they are due. From Future it gets get(), cancel() and the other result methods.

2. ScheduledFuture Hierarchy

ScheduledFuture interface hierarchyScheduledFuture extends Delayed and Future. Delayed extends java.lang.Comparable of Delayed. RunnableScheduledFuture extends ScheduledFuture.«interface» · java.langComparable<Delayed>compareTo(Delayed)«interface»DelayedgetDelay(TimeUnit)«interface»Future<V>get(), cancel(…), isDone()«interface»ScheduledFuture<V>this page«no methods of its own»«interface»RunnableScheduledFuture<V>isPeriodic()extendsinterfacejava.lang type

Swipe sideways to see the whole diagram.

  • Delayed (interface): Provides getDelay(TimeUnit): the remaining delay, zero or negative once the task is due.
  • Comparable<Delayed> (java.lang interface): Lets scheduled tasks be sorted by remaining delay.
  • Future (interface): Provides get(), cancel(), isDone() and the Java 19 state methods.
  • RunnableScheduledFuture (interface): Used inside scheduled executors; adds isPeriodic().

3. Key Methods (Inherited)

MethodFromDescription
long getDelay(TimeUnit unit)DelayedRemaining delay in the given unit.
int compareTo(Delayed o)ComparableOrders tasks by remaining delay.
V get()FutureWaits for the result of a one-shot task.
boolean cancel(boolean)FutureCancels a pending or periodic task.
isDone(), isCancelled()FutureReport completion and cancellation.

4. Example: Counting Down to a Scheduled Task

MaintenanceCountdown.java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class MaintenanceCountdown {

    static long roundedMillis(ScheduledFuture<?> f) {
        return Math.round(f.getDelay(TimeUnit.MILLISECONDS) / 100.0) * 100;   // nearest 100 ms
    }

    public static void main(String[] args) throws InterruptedException {
        try (ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor()) {
            ScheduledFuture<?> maintenance = scheduler.schedule(
                    () -> System.out.println("Putting the shop into maintenance mode"), 2, TimeUnit.SECONDS);

            System.out.println("Maintenance starts in ~" + roundedMillis(maintenance) + " ms");
            Thread.sleep(500);
            System.out.println("Maintenance starts in ~" + roundedMillis(maintenance) + " ms");

            // The release was postponed: cancel the pending maintenance
            boolean cancelled = maintenance.cancel(false);
            System.out.println("Cancelled: " + cancelled + ", isDone: " + maintenance.isDone());
        }
    }
}
Output
Maintenance starts in ~2000 ms
Maintenance starts in ~1500 ms
Cancelled: true, isDone: true

How the code works

  1. schedule() returns a ScheduledFuture<?> for a task due in 2 seconds.
  2. getDelay(MILLISECONDS) reports the time left; the example rounds it to 100 ms because the exact value depends on timing.
  3. After 500 ms, about 1,500 ms remain. cancel(false) then removes the need to run the task at all.
  4. A cancelled task counts as done, so isDone() is true, and the maintenance message never prints.

5. Example: Finding the Next Job to Run

NextJobFirst.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class NextJobFirst {

    public static void main(String[] args) {
        try (ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1)) {
            Map<ScheduledFuture<?>, String> jobs = new LinkedHashMap<>();
            jobs.put(scheduler.schedule(() -> { }, 30, TimeUnit.MINUTES), "rotate logs");
            jobs.put(scheduler.schedule(() -> { }, 5, TimeUnit.MINUTES), "send digest email");
            jobs.put(scheduler.schedule(() -> { }, 2, TimeUnit.HOURS), "rebuild sitemap");

            // ScheduledFuture extends Delayed, which is Comparable<Delayed>: sorts by remaining delay
            List<ScheduledFuture<?>> byDelay = new ArrayList<>(jobs.keySet());
            byDelay.sort(null);

            for (ScheduledFuture<?> f : byDelay) {
                System.out.printf("%-18s in %3d min%n", jobs.get(f), Math.round(f.getDelay(TimeUnit.SECONDS) / 60.0));
            }
            scheduler.shutdownNow();     // discard the pending demo jobs
        }
    }
}
Output
send digest email  in   5 min
rotate logs        in  30 min
rebuild sitemap    in 120 min

How the code works

  1. Three jobs are scheduled in an arbitrary order: 30 minutes, 5 minutes and 2 hours ahead.
  2. byDelay.sort(null) uses natural ordering, which for ScheduledFuture means compareTo() from Delayed: the shortest remaining delay first.
  3. shutdownNow() discards the pending demo jobs so the program can exit immediately.

6. Common Mistakes and Best Practices

  • Calling get() on a periodic task. It never completes normally, so get() blocks until the task is cancelled or fails.
  • Treating getDelay() as exact. It is a snapshot that changes every moment, and tasks may start a little after the delay elapses.
  • Losing the handle. Keep the ScheduledFuture if you may need to cancel the task later.
  • Many cancelled long-delay tasks. On a ScheduledThreadPoolExecutor, enable setRemoveOnCancelPolicy(true) so they leave the queue immediately.

7. Summary

  • ScheduledFuture<V> extends Delayed and Future<V> and adds no methods of its own.
  • getDelay() returns the remaining delay; scheduled futures sort by it through Comparable<Delayed>.
  • Use get() for one-shot tasks and cancel() to stop pending or periodic ones.

Related Tutorials

8. References