1. 概要

In this tutorial, we’ll discuss the Spring task scheduling mechanism, TaskScheduler, and it’s pre-built implementations. Then we’ll explore the different triggers to use. To read more about scheduling in Spring, can check out these @Async and @Scheduled articles.

Spring 3.0 introduced TaskScheduler with a variety of methods designed to run at some point in the future. TaskScheduler also returns a representation object of the ScheduledFuture interface, which we can use to cancel scheduled tasks and check to see if they’re done or not.

All we need to do is select a runnable task for scheduling, then select a proper scheduling policy.

2. ThreadPoolTaskScheduler

ThreadPoolTaskScheduler is useful for internal thread management, as it delegates tasks to the ScheduledExecutorService, and implements the TaskExecutor interface. A single instance of it is able to handle asynchronous potential executions, as well as the @Scheduled annotation.

Let’s define the ThreadPoolTaskScheduler bean at ThreadPoolTaskSchedulerConfig:

@Configuration
@ComponentScan(
  basePackages="com.baeldung.taskscheduler",
  basePackageClasses={ThreadPoolTaskSchedulerExamples.class})
public class ThreadPoolTaskSchedulerConfig {

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
        ThreadPoolTaskScheduler threadPoolTaskScheduler
          = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(5);
        threadPoolTaskScheduler.setThreadNamePrefix(
          "ThreadPoolTaskScheduler");
        return threadPoolTaskScheduler;
    }
}

構成されたBeanthreadPoolTaskScheduler は、構成されたプールサイズ5に基づいて非同期でタスクを実行できます。

ThreadPoolTaskScheduler に関連するすべてのスレッド名には、ThreadPoolTaskSchedulerというプレフィックスが付けられることに注意してください。

次にスケジュールできる簡単なタスクを実装しましょう。

class RunnableTask implements Runnable{
    private String message;
    
    public RunnableTask(String message){
        this.message = message;
    }
    
    @Override
    public void run() {
        System.out.println(new Date()+" Runnable Task with "+message
          +" on thread "+Thread.currentThread().getName());
    }
}

We can now schedule the scheduler to execute this task:

taskScheduler.schedule(
  new Runnabletask("Specific time, 3 Seconds from now"),
  new Date(System.currentTimeMillis + 3000)
);

taskScheduler は、この実行可能なタスクを、現在の時刻からちょうど3秒後の既知の日付にスケジュールします。

Now let’s go a bit more in-depth with the ThreadPoolTaskScheduler scheduling mechanisms.

3. 実行可能なタスクを固定遅延でスケジュールする

We can schedule a fixed delay with two simple mechanisms:

3.1. 最後にスケジュールされた実行の固定遅延後のスケジュール

Let’s configure a task to run after a fixed delay of 1000 milliseconds:

taskScheduler.scheduleWithFixedDelay(
  new RunnableTask("Fixed 1 second Delay"), 1000);

RunnableTask は、ある実行が完了してから次の実行が開始されるまで、常に1000ミリ秒後に実行されます。

3.2. 特定の日付の固定遅延後のスケジュール

特定の開始時間の固定遅延後に実行するようにタスクを構成しましょう。

taskScheduler.scheduleWithFixedDelay(
  new RunnableTask("Current Date Fixed 1 second Delay"),
  new Date(),
  1000);

The RunnableTask will be invoked at the specified execution time, which encompasses the time in which the @PostConstruct method starts, and subsequently with 1000 milliseconds delay.

4. 固定レートでのスケジューリング

There are two simple mechanisms for scheduling runnable tasks at a fixed rate.

4.1. RunnableTaskを固定レートでスケジュールする

固定レートのミリ秒で実行するタスクをスケジュールしましょう。

taskScheduler.scheduleAtFixedRate(
  new RunnableTask("Fixed Rate of 2 seconds") , 2000);

The next RunnableTask will always run after 2000 milliseconds, regardless of the status of the last execution, which may still be running.

4.2. RunnableTaskを特定の日付から固定レートでスケジュールする

taskScheduler.scheduleAtFixedRate(new RunnableTask(
  "Fixed Rate of 2 seconds"), new Date(), 3000);

RunnableTask は、現在の時刻から3000ミリ秒後に実行されます。

5. CronTriggerを使用したスケジューリング

We use CronTrigger to schedule a task based on a cron expression:

CronTrigger cronTrigger 
  = new CronTrigger("10 * * * * ?");

We can use the provided trigger to run a task according to a certain specified cadence or schedule:

taskScheduler.schedule(new RunnableTask("Cron Trigger"), cronTrigger);

この場合、RunnableTaskは毎分の10秒に実行されます。

6. Scheduling With PeriodicTrigger

PeriodicTrigger を使用して、固定遅延が2000ミリ秒のタスクをスケジュールしてみましょう。

PeriodicTrigger periodicTrigger 
  = new PeriodicTrigger(2000, TimeUnit.MICROSECONDS);

The configured PeriodicTrigger bean is used to run a task after a fixed delay of 2000 milliseconds.

次に、RunnableTaskPeriodicTriggerでスケジュールしましょう。

taskScheduler.schedule(
  new RunnableTask("Periodic Trigger"), periodicTrigger);

We can also configure PeriodicTrigger to be initialized at a fixed rate, rather than a fixed delay. Furthermore, we can set an initial delay for the first scheduled task by a given milliseconds.

All we need to do is add two lines of code before the return statement at the periodicTrigger bean:

periodicTrigger.setFixedRate(true);
periodicTrigger.setInitialDelay(1000);

We used the setFixedRate method to schedule the task at a fixed rate, rather than with a fixed delay. Then we used the setInitialDelay method to set an initial delay for the first runnable task to run.

7. 結論

In this brief article, we learned how to schedule a runnable task using the Spring support for tasks.

We demonstrated running the task with a fixed delay, at a fixed rate, and according to a specified trigger.

As always, the code is available as a Maven project over in GitHub.