DEV Community

Edem Agbenyo
Edem Agbenyo

Posted on • Updated on

100 Days of Java: Day 3 Scheduler

Welcome to Day 3 of the 100 Days Java! Today, we'll be exploring a Java code snippet that demonstrates how we can schedule a task to execute periodically using ScheduledExecutorService. Here is the code that implements scheduling:

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

public class Day003 {

    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) throws InterruptedException {
        var day003 = new Day003();
        day003.printCurrentTimeEvery2Seconds();
        Thread.sleep(15_000);
        day003.stopPrinting();
    }

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

    public void stopPrinting() {
        scheduledExecutorService.shutdown();
    }

}
Enter fullscreen mode Exit fullscreen mode

To begin, we import necessary classes from the Java standard libraries, including LocalTime for time-related operations, and Executors and ScheduledExecutorService for task scheduling.

Next, we define a class called Day003. This class contains a ScheduledExecutorService object called scheduledExecutorService, which is responsible for scheduling and executing tasks.

Moving on to the main method, which is the entry point of our program. Inside this method, we create an instance of the Day003 class named day003.

We then call the printCurrentTimeEvery2Seconds method on our day003 object. This method schedules a task to print the current time every 2 seconds. The task is defined using a lambda expression, which simply prints the current time using LocalTime.now().

After scheduling the task, we introduce a delay using Thread.sleep(15_000) to allow the task to run for 15 seconds.

Finally, we call the stopPrinting method on our day003 object to stop the execution of the scheduled task.

Let's summarize what this code does. When we run this program, it will start printing the current time every 2 seconds using LocalTime.now(). This is achieved by scheduling a task with the ScheduledExecutorService to execute at a fixed rate of every 2 seconds. The task is stopped after running for 15 seconds.

This code snippet showcases how to use ScheduledExecutorService to schedule and execute tasks at specified intervals. It is a powerful feature that can be utilized for various timed operations and background tasks in your Java applications.

That's it for Day 3! Stay tuned for the next code snippet and explanation tomorrow. Happy coding!

Code credits: https://github.com/hbelmiro

Top comments (0)