SchduleWithFixedDelay and SchduleAtFixedRate of Trample Series

Keywords: Java less

Understanding timed and delayed tasks

  • Scheduled ExecutorService#scheduleAtFixedRate() refers to execution at a fixed frequency, and period refers to the time between two successful executions.The time at which the previous task starts, after a period, detects whether the previous task has been completed, if the previous task has been completed, the current task will be executed immediately, and if the previous task has not been completed, it will need to be executed immediately after the previous task has been executed.
  • Scheduled ExecutorService#scheduleWithFixedDelay() refers to execution with a fixed delay, which refers to the delay between the end of one execution and the start of the next.

Example

scheduleAtFixedRate

public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(
            "my-test-pool-%d").build();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, threadFactory);
        Date startTime = new Date();
        System.out.println("startTime: " + startTime.toString());
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            System.out.println("beginTime: " + new Date().toString());
            try {
                Thread.sleep(5 * 1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("endTime: " + new Date().toString());
        }, 2, 3, TimeUnit.SECONDS);
    }

Output:

startTime: Sun Feb 16 11:17:09 CST 2020
beginTime: Sun Feb 16 11:17:11 CST 2020
endTime: Sun Feb 16 11:17:16 CST 2020
beginTime: Sun Feb 16 11:17:16 CST 2020
endTime: Sun Feb 16 11:17:21 CST 2020
beginTime: Sun Feb 16 11:17:21 CST 2020
endTime: Sun Feb 16 11:17:26 CST 2020
beginTime: Sun Feb 16 11:17:26 CST 2020
endTime: Sun Feb 16 11:17:31 CST 2020
beginTime: Sun Feb 16 11:17:31 CST 2020
endTime: Sun Feb 16 11:17:36 CST 2020
beginTime: Sun Feb 16 11:17:36 CST 2020

The current task execution time is greater than or equal to the interval time, and the next task executes immediately after the task executes.Equivalent to continuous execution.

scheduleWithFixedDelay

public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(
            "my-test-pool-%d").build();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, threadFactory);
        Date startTime = new Date();
        System.out.println("startTime: " + startTime.toString());
        scheduledExecutorService.scheduleWithFixedDelay(() -> {
            System.out.println("beginTime: " + new Date().toString());
            try {
                Thread.sleep(5 * 1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("endTime: " + new Date().toString());
        }, 2, 3, TimeUnit.SECONDS);
    }

Output:

startTime: Sun Feb 16 11:27:26 CST 2020
beginTime: Sun Feb 16 11:27:28 CST 2020
endTime: Sun Feb 16 11:27:33 CST 2020
beginTime: Sun Feb 16 11:27:36 CST 2020
endTime: Sun Feb 16 11:27:41 CST 2020
beginTime: Sun Feb 16 11:27:44 CST 2020
endTime: Sun Feb 16 11:27:49 CST 2020
beginTime: Sun Feb 16 11:27:52 CST 2020

Whenever the last task is completed, it is executed at an interval of time.Execution is the same whether the current task takes longer than, equal to, or less than the interval.

Common pits

With regard to timed thread pools (scheduleAtFixedRate for timed tasks and scheduleWithFixedDelay for deferred tasks), many people think that a set frequency (such as 1Min) is set and that it will work on schedule at this interval.However, if one of the scheduled tasks gets stuck, not only will the schedule fail, but the entire thread pool will also stop on the schedule.

Example

If an exception is thrown in the run method without being caught, the entire timer task gets stuck.It is recommended that try...catch...fianlly...be used throughout the run method.

public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(
            "my-test-pool-%d").build();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1, threadFactory);
        Date startTime = new Date();
        System.out.println("startTime: " + startTime.toString());
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            System.out.println("beginTime: " + new Date().toString());
            try {
                Thread.sleep(5 * 1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("endTime: " + new Date().toString());
            throw new NullPointerException();
        }, 2, 3, TimeUnit.SECONDS);
    }

Posted by ade234uk on Sun, 23 Feb 2020 19:51:38 -0800