概要
指定された初期遅延時間(最初の実行までの遅延時間)の後にタスクを実行し、その後一定の間隔でタスクを繰り返し実行するためのメソッド。
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
引数について
このメソッドは、Runnable
オブジェクト(またはCallable
オブジェクト)を受け取る。
-
initialDelay
:初期遅延時間 -
period
:インターバル時間(タスクの繰り返し実行の間隔) -
unit
:遅延時間と間隔の単位を表すTimeUnit
列挙型
例
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleAtFixedRateExample {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
System.out.println("Task executed at fixed rate");
};
// 初期遅延時間: 1秒, 実行間隔: 2秒
executorService.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);
}
}
上記の例では、newScheduledThreadPool()
メソッドを使用してScheduledExecutorService
のインスタンスを作成している。。
Runnable
オブジェクトを作成し、それをscheduleAtFixedRate()
メソッドに渡してタスクをスケジュールしている。
この例では、最初の実行までの遅延時間を1秒、タスクの繰り返し実行の間隔を2秒として指定している。
したがって、最初の実行は1秒後に行われ、その後は2秒ごとにタスクが繰り返し実行される。
実行結果
Task executed at fixed rate
Task executed at fixed rate
Task executed at fixed rate
...
scheduleAtFixedRate()
メソッドによって指定されたタスクは、指定された初期遅延時間の後に実行され、その後一定の間隔で繰り返し実行される。
定期的な処理の実行を中断するには以下の方法がある。
①shutdown
メソッドでシャットダウンする。
②ScheduledFuture
インタフェースのcancel
メソッドが呼ばれる。
③例外がスローされる。
インターバルよりも処理の時間がかかった場合はその終了を待って実行される。
つまり、並行で実行されることはなく、前の処理と次の処理との間隔が一定ではない。
処理の長さに関係なく、インターバルを一定にしたい場合はscheduleWithFixedDelayメソッドを使用する。