DEV Community

Edem Agbenyo
Edem Agbenyo

Posted on • Edited on

2

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay