0
0

More than 1 year has passed since last update.

【JavaGold】scheduleAtFixedRateメソッド

Last updated at Posted at 2023-07-13

概要

指定された初期遅延時間(最初の実行までの遅延時間)の後にタスクを実行し、その後一定の間隔でタスクを繰り返し実行するためのメソッド。

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メソッドを使用する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0