java concurrency scheduling tasks to execute after a given delay or periodically

h‮ww//:sptt‬w.theitroad.com

In Java, the java.util.concurrent.ScheduledExecutorService interface provides a way to schedule tasks to execute after a given delay or periodically at a fixed rate or with a fixed delay between each execution.

Here's an example of how to use ScheduledExecutorService to schedule a task to execute after a delay:

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

public class ScheduledExecutorServiceExample {
    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        Runnable task = () -> {
            System.out.println("Task executed after a delay");
        };

        executor.schedule(task, 5, TimeUnit.SECONDS);

        executor.shutdown();
    }
}

In this example, we create a ScheduledExecutorService with a single thread. We define a Runnable task that prints a message to the console. We then use the schedule() method of the ScheduledExecutorService to schedule the task to execute after a delay of 5 seconds.

Note that we call shutdown() on the ScheduledExecutorService after scheduling the task. This is important to ensure that the ScheduledExecutorService is properly shut down and that any resources it has acquired are released.

Here's an example of how to use ScheduledExecutorService to schedule a task to execute periodically at a fixed rate:

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

public class ScheduledExecutorServiceExample {
    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        Runnable task = () -> {
            System.out.println("Task executed periodically");
        };

        executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);

        // Sleep for 10 seconds to allow the task to execute multiple times
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executor.shutdown();
    }
}

In this example, we use the scheduleAtFixedRate() method of the ScheduledExecutorService to schedule the task to execute periodically at a fixed rate of 1 second. We then sleep the main thread for 10 seconds to allow the task to execute multiple times. Finally, we call shutdown() on the ScheduledExecutorService to ensure that it is properly shut down.