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();
timePrinter.printCurrentTimeEvery2Seconds();
Thread.sleep(15_000);
timePrinter.stopPrinting();
}
public void printCurrentTimeEvery2Seconds() {
Runnable task = () -> System.out.println(LocalTime.now());
scheduledExecutorService.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS);
}
public void stopPrinting() {
scheduledExecutorService.shutdown();
}
}
If you have any questions, leave a comment or ask me on my social media.
