Spring Frameworkでは定期的な処理実行を実現するためのスケジュール機能が提供されています。バッチ処理や定期的なデータ更新など、様々なビジネスロジックの自動実行に利用できます。
1. 必要な依存関係の追加
Mavenプロジェクトの場合、pom.xmlファイルに以下の依存関係を追加します:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-task</artifactId>
</dependency>
Spring Bootアプリケーションでは、基本的なスケジュール機能はspring-boot-starter-webに含まれています。
2. スケジュール設定の基本構成
2.1 @EnableSchedulingの適用
スケジュール機能を有効にするには、アプリケーションのメインクラスまたは設定クラスに@EnableSchedulingアノテーションを追加します:import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
2.2 タスクメソッドの定義
スケジュール実行するメソッドを@Componentクラス内に定義し、@Scheduledアノテーションで実行間隔を指定します:import org.springframework.scheduling.annotation.Scheduled;
@Component
public class TimeBasedTasks {
@Scheduled(fixedInterval = 3000)
public void displayTimestamp() {
System.out.println("実行時刻: " + Instant.now());
}
@Scheduled(cronExpression = "0 30 9 * * MON-FRI")
public void processDailyData() {
System.out.println("平日のデータ処理を実行");
}
}
- fixedInterval:実行間隔をミリ秒単位で指定
- cronExpression:Cron式を使用した詳細なスケジュール設定
3. Cron式の詳細設定
Cron式は6つのフィールド(秒、分、時、日、月、曜日)で構成され、複雑な実行パターンを定義できます。 - 特殊文字の意味: - *:全ての値に一致 - ,:値のリストを指定(例:1,3,5) - -:値の範囲を指定(例:1-5) - /:増分値を指定(例:0/15)4. カスタムスケジューラの設定
スレッドプールのサイズなど、スケジューラの動作をカスタマイズする場合はTaskScheduler Beanを定義します:@Configuration
public class SchedulerConfiguration {
@Bean
public ThreadPoolTaskScheduler customScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setThreadCount(5);
scheduler.setThreadNamePrefix("scheduled-task-");
return scheduler;
}
}