w3resource

Java Scheduled Task Execution with ScheduledExecutorService

Java Multithreading: Exercise-13 with Solution

Write a Java program that uses the ScheduledExecutorService interface to schedule tasks for execution at a specified time or with a fixed delay.

Sample Solution:

Java Code:

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

public class ScheduledExecutorExercise {

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

    // Schedule a task to run after a delay of 2 seconds
    executor.schedule(new Task(), 2, TimeUnit.SECONDS);

    // Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds
    executor.scheduleAtFixedRate(new Task(), 3, 5, TimeUnit.SECONDS);

    // Wait for scheduled tasks to complete
    try {
      Thread.sleep(15000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Shutdown the executor
    executor.shutdown();
  }

  static class Task implements Runnable {
    @Override
    public void run() {
      System.out.println("Task executed at: " + new Date());
    }
  }
}

Sample Output:

Task executed at: Wed Jul 15 08:25:12 IST 2020
Task executed at: Wed Jul 15 08:25:13 IST 2020
Task executed at: Wed Jul 15 08:25:18 IST 2020
Task executed at: Wed Jul 15 08:25:23 IST 2020

Explanation:

In the above exercise -

  • First, we create a ScheduledExecutorService using Executors.newScheduledThreadPool(1) to create a thread pool with a single worker thread.
  • Schedule a task to run after a delay of 2 seconds using the schedule() method. This task is executed only once.
  • Next schedule a task to run after a delay of 3 seconds and repeat every 5 seconds using the scheduleAtFixedRate() method. This task is executed repeatedly at a fixed rate.
  • To allow scheduled tasks to execute, we use Thread.sleep() to pause the main thread for 15 seconds.
  • Finally, we shutdown the executor using the shutdown() method to release its resources.

Flowchart:

Flowchart: Java Scheduled Task Execution with ScheduledExecutorService.
Flowchart: Java Scheduled Task Execution with ScheduledExecutorService.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Asynchronous Task Execution in Java with Callable and Future.
Next: Parallel Recursive Task Execution in Java with ForkJoinPool.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/multithreading/java-multithreading-exercise-13.php