Skip to main content

How do I execute tasks at scheduled intervals

In this Q&A, we'll go over how to execute tasks at scheduled intervals.

As usual ExecutorService comes to the rescue.  ScheduledThreadPoolExecutor provides ability to execute tasks in a thread pool at scheduled rate or at scheduled period.

See example code below.

package com.javahowdoi.thread;

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

public class SchedulerDemo {
    public static void main(String[] args ) throws InterruptedException {
        ScheduledExecutorService es = Executors.newScheduledThreadPool(1);
        // executes threads at scheduled rate
        es.scheduleAtFixedRate(() -> System.out.println("beep"), 1, 1, TimeUnit.SECONDS);
        Thread.sleep(5000);
        es.shutdown();
    }
}

Comments