Executors newSingleThreadScheduledExecutor() Method Example

Introduction

The Executors.newSingleThreadScheduledExecutor() method in Java creates a single-threaded executor that can schedule commands to run after a given delay or to execute periodically. This is useful for tasks that need to be executed at regular intervals or after a specific delay.

Table of Contents

  1. Overview of newSingleThreadScheduledExecutor Method
  2. Creating a Single-Thread Scheduled Executor
  3. Scheduling Tasks
    • Scheduling with a Fixed Delay
    • Scheduling at a Fixed Rate
  4. Example: Using newSingleThreadScheduledExecutor
  5. Shutting Down the Executor
  6. Conclusion

1. Overview of newSingleThreadScheduledExecutor Method

The newSingleThreadScheduledExecutor method returns a ScheduledExecutorService object that can schedule commands to run after a given delay or periodically. This executor uses a single worker thread.

Syntax:

public static ScheduledExecutorService newSingleThreadScheduledExecutor()

2. Creating a Single-Thread Scheduled Executor

To create a single-thread scheduled executor, use the newSingleThreadScheduledExecutor method.

Example:

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

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

        // Your scheduled tasks go here

        executorService.shutdown();
    }
}

3. Scheduling Tasks

Scheduling with a Fixed Delay

Schedules a task to run repeatedly with a fixed delay between the end of the last execution and the start of the next.

Syntax:

ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

Example:

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

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

        executorService.scheduleWithFixedDelay(() -> {
            System.out.println("Task executed at " + System.currentTimeMillis());
        }, 0, 1, TimeUnit.SECONDS);

        // ExecutorService should be shut down appropriately in a real application
    }
}

Scheduling at a Fixed Rate

Schedules a task to run repeatedly at a fixed rate, with the specified period between successive executions.

Syntax:

ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

Example:

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

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

        executorService.scheduleAtFixedRate(() -> {
            System.out.println("Task executed at " + System.currentTimeMillis());
        }, 0, 1, TimeUnit.SECONDS);

        // ExecutorService should be shut down appropriately in a real application
    }
}

4. Example: Using newSingleThreadScheduledExecutor

Let's create a complete example that demonstrates how to use newSingleThreadScheduledExecutor to schedule tasks with both fixed delay and fixed rate.

Example:

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

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

        Runnable task1 = () -> {
            System.out.println("Fixed Delay Task executed at " + System.currentTimeMillis());
        };

        Runnable task2 = () -> {
            System.out.println("Fixed Rate Task executed at " + System.currentTimeMillis());
        };

        // Schedule task1 with a fixed delay of 1 second
        executorService.scheduleWithFixedDelay(task1, 0, 1, TimeUnit.SECONDS);

        // Schedule task2 at a fixed rate of 1 second
        executorService.scheduleAtFixedRate(task2, 0, 1, TimeUnit.SECONDS);

        // Let the tasks run for 10 seconds for demo purposes
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Shutdown the executor service
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }

        System.out.println("Executor service shut down.");
    }
}

Output:

Fixed Delay Task executed at 1620200000000
Fixed Rate Task executed at 1620200000000
Fixed Rate Task executed at 1620200001000
Fixed Delay Task executed at 1620200001000
Fixed Rate Task executed at 1620200002000
Fixed Rate Task executed at 1620200003000
Fixed Delay Task executed at 1620200002000
Fixed Rate Task executed at 1620200004000
Fixed Delay Task executed at 1620200003000
...
Executor service shut down.

Explanation:

  • task1 is scheduled with a fixed delay of 1 second between the end of one execution and the start of the next.
  • task2 is scheduled to run at a fixed rate of 1 second between the start of successive executions.
  • The main thread sleeps for 10 seconds to let the tasks execute, then shuts down the executor service.

5. Shutting Down the Executor

It's important to properly shut down the ScheduledExecutorService to release resources.

Graceful Shutdown:

executorService.shutdown();
try {
    if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
        executorService.shutdownNow();
    }
} catch (InterruptedException e) {
    executorService.shutdownNow();
}

Forceful Shutdown:

executorService.shutdownNow();

6. Conclusion

The Executors.newSingleThreadScheduledExecutor method provides a convenient way to create a single-threaded scheduled executor that can schedule tasks to run after a delay or periodically. By using this method, you can efficiently manage and execute scheduled tasks in your applications. Properly managing the lifecycle of the executor service, including shutting it down, is crucial to avoid resource leaks.

Happy coding!

Comments