Java ScheduledExecutorService Guide

ScheduledExecutorService is an ExecutorService used for executing scheduled tasks. To configure a ScheduledExecutorService, you can create an instance using the newScheduledThreadPool method from the Executors class and submit the tasks that need to be executed to it.

For example, here is a simple sample code to configure and use ScheduledExecutorService:

import java.util.concurrent.*;

public class ScheduledExecutorExample {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

        scheduledExecutorService.scheduleAtFixedRate(() -> {
            System.out.println("Executing task at " + System.currentTimeMillis());
        }, 0, 1, TimeUnit.SECONDS);

        // 可以添加更多的任务
        scheduledExecutorService.schedule(() -> {
            System.out.println("Another task executed at " + System.currentTimeMillis());
        }, 5, TimeUnit.SECONDS);
    }
}

In this example, we have created a ScheduledExecutorService instance and used the scheduleAtFixedRate method to execute a task every 1 second. We have also used the schedule method to execute another task after 5 seconds.

You can adjust the configuration of ScheduledExecutorService according to your own needs, such as thread pool size, task execution interval, etc. For more information on the methods and configurations of ScheduledExecutorService, please refer to the official documentation.

bannerAds