Executors and thread pools · Topic 4 of 7
Scheduled executor
Definition​
A ScheduledExecutorService runs a task after a delay or repeatedly at a fixed rate. It replaces older Timer code and keeps running other tasks even if one of them fails.
Example code​
A task that runs three times, once a moment
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class Demo {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
AtomicInteger runs = new AtomicInteger();
CountDownLatch threeRuns = new CountDownLatch(3);
scheduler.scheduleAtFixedRate(() -> {
System.out.println("tick " + runs.incrementAndGet());
threeRuns.countDown();
}, 0, 100, TimeUnit.MILLISECONDS); // start now, then every 100 ms
threeRuns.await();
scheduler.shutdownNow();
}
}
// Output:
// tick 1
// tick 2
// tick 3
Finished this page? Track your progress (saved only in your browser).