Java SE API

ScheduledExecutorService.schedule(Callable, long, TimeUnit)

Schedule one result-bearing task after a relative delay.

Formal Syntax & Structure

java syntaxjava
<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)

Parameters & Attributes

NameTypeDescription
unitTimeUnitTime unit for the supplied duration
delaylongRelative scheduling delay

Working Example

Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {    static void stop(ExecutorService pool) throws InterruptedException {        pool.shutdown();        try {            if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {                for (Runnable pending : pool.shutdownNow()) {                    if (pending instanceof Future<?> future) future.cancel(false);                }                if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running");            }        } catch (InterruptedException e) {            for (Runnable pending : pool.shutdownNow()) {                if (pending instanceof Future<?> future) future.cancel(false);            }            throw e;        }    }    public static void main(String[] args) throws Exception {        ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();        try {            ScheduledFuture<String> result = timer.schedule(() -> "report ready", 0, TimeUnit.MILLISECONDS);            System.out.println(result.get(3, TimeUnit.SECONDS));        } finally { stop(timer); }    }}
Java Reference