Skip to content
Home » How to Schedule a Task to Run Periodically in Java

How to Schedule a Task to Run Periodically in Java

clear glass with red sand grainer

Here’s how to schedule a task to run periodically in Java.

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

public class TimePrinter {

    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) throws InterruptedException {
        var timePrinter = new TimePrinter();

    public void printCurrentTimeEvery2Seconds() {
        Runnable task = () -> System.out.println(;
        scheduledExecutorService.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS);

    public void stopPrinting() {

If you have any questions, leave a comment or ask me on my social media.