Java - How to use ScheduledThreadPoolExecutor

If you need to perform some task after a certain amount of time delay, or if you need to run it periodically at regular time intervals, you might want to consider a ScheduledThreadPoolExecutor.

ScheduledThreadPoolExecutor provides the following 4 methods.

  • schedule(Runnable command, long delay, TimeUnit unit) : Execute the task once after a certain amount of time
  • schedule(Callable command, long delay, TimeUnit unit) : Executes the task once after a certain period of time and returns the result
  • scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) : Executes the task repeatedly at regular time intervals.
  • scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit) : When the task is completed, it is executed again after a certain period of time. The difference from scheduleAtFixedRate() is that the end of the task is the standard.

schedule(Runnable)

schedule() is a method that executes a Job after a certain time (delay).

The arguments passed to schedule() are as follows.

  • Runnable: Receives a Runnable with no return value as an argument
  • delay : the amount of time to delay
  • TimeUnit : The unit of time
package concurrent;

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

public class ScheduledThreadPoolExecutorExample1 {

    public static void main(String[] args) {

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
        Runnable runnable = () -> System.out.println("Runnable task : " + LocalTime.now());
        int delay = 3;

        // schedule the job
        System.out.println("Scheduled task : " + LocalTime.now() );
        executor.schedule(runnable, delay, TimeUnit.SECONDS);
    }
}

result

Scheduled task : 22:58:43.006
Runnable task : 22:58:46.007

schedule(Callable)

schedule() is a method that executes a Job after a certain period of time.

The arguments passed to schedule() are as follows.

  • Callable : Callable returning T receive as a character
  • delay : the amount of time to delay
  • TimeUnit : The unit of time

schedule() is called ScheduledFuture and when the job is completed, you can get the return value with ScheduledFuture.get().

package concurrent;

import java.time.LocalTime;
import java.util.concurrent.*;

public class ScheduledThreadPoolExecutorExample2 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
        Callable<String> callable =  () -> "Callable task : " + LocalTime.now();
        int delay = 3;

        // schedule the job
        System.out.println("Scheduled task : " + LocalTime.now() );
        ScheduledFuture<String> future =
            executor.schedule(callable, delay, TimeUnit.SECONDS);

        // Wait for results to be returned
        String result = future.get();
        System.out.println(result);
    }
}

result

Scheduled task : 23:00:00.025
Callable task : 23:00:03.027

scheduleAtFixedRate()

scheduleAtFixedRate() is a method that runs a task at regular time intervals.

The arguments passed to scheduleAtFixedRate() are as follows.

  • Runnable: Receives a Runnable with no return value as an argument
  • initialDelay : The time to wait when the job is first executed
  • delay : the time interval for the job to run
  • TimeUnit : The unit of time

If you look at the result of the following example, you can see that after the job is executed (regardless of the completion time), the job is executed again after a certain delay.

package concurrent;

import java.time.LocalTime;
import java.util.concurrent.*;

public class ScheduledThreadPoolExecutorExample3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
        Runnable runnable = () -> {
            System.out.println("++ Repeat task : " + LocalTime.now());
            sleepSec(3);
            System.out.println("-- Repeat task : " + LocalTime.now());
        };
        int initialDelay = 2;
        int delay = 3;

        // schedule the job
        System.out.println("Scheduled task : " + LocalTime.now() );
        executor.scheduleAtFixedRate(
            runnable, initialDelay, delay, TimeUnit.SECONDS);
    }

    private static void sleepSec(int sec) {
        try {
            TimeUnit.SECONDS.sleep(sec);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

result

Scheduled task : 23:01:48.967
++ Repeat task : 23:01:50.969
-- Repeat task : 23:01:53.969
++ Repeat task : 23:01:53.970
-- Repeat task : 23:01:56.970
++ Repeat task : 23:01:56.971
-- Repeat task : 23:01:59.971
++ Repeat task : 23:01:59.971
-- Repeat task : 23:02:02.972
++ Repeat task : 23:02:02.972
-- Repeat task : 23:02:05.972
++ Repeat task : 23:02:05.973
-- Repeat task : 23:02:08.973
....

scheduleWithFixedDelay()

scheduleAtFixedRate() is a method that executes the job again after a certain period of time after the job is completed.

The arguments passed to scheduleWithFixedDelay() are as follows.

  • Runnable: Receives a Runnable with no return value as an argument
  • initialDelay : The time to wait when the job is first executed
  • delay : The amount of time to wait until the next job is executed after a job is completed
  • TimeUnit : The unit of time

If you look at the result of the following example, you can see that the next job is executed after waiting for delay after the job is finished.

package concurrent;

import java.time.LocalTime;
import java.util.concurrent.*;

public class ScheduledThreadPoolExecutorExample4 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
        Runnable runnable = () -> {
            System.out.println("++ Repeat task : " + LocalTime.now());
            sleepSec(3);
            System.out.println("-- Repeat task : " + LocalTime.now());
        };
        int initialDelay = 2;
        int delay = 3;

        // schedule the job
        System.out.println("Scheduled task : " + LocalTime.now() );
        executor.scheduleWithFixedDelay(
            runnable, initialDelay , delay, TimeUnit.SECONDS);
    }

    private static void sleepSec(int sec) {
        try {
            TimeUnit.SECONDS.sleep(sec);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

result

Scheduled task : 23:03:29.282
++ Repeat task : 23:03:31.284
-- Repeat task : 23:03:34.285
++ Repeat task : 23:03:37.285
-- Repeat task : 23:03:40.286
++ Repeat task : 23:03:43.286
-- Repeat task : 23:03:46.286
++ Repeat task : 23:03:49.287
-- Repeat task : 23:03:52.287
++ Repeat task : 23:03:55.288
-- Repeat task : 23:03:58.288
++ Repeat task : 23:04:01.288
-- Repeat task : 23:04:04.289
....
codechachaCopyright ©2019 codechacha