【Spring】Scheduling Tasks
Spring Webアプリで定期実行処理を実現するためには、ScheduledTasksを使う。便利。
Applicationクラスに@EnableSchedulingを追加する
@SpringBootApplication @EnableScheduling public class StsTodoApplication { ... }
コンポーネント作成
@Component @Slf4j public class ScheduledTasks { @Scheduled(fixedRate = 60000) public void reportCurrentTime() { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); log.info("The time is now {}", dateFormat.format(new Date())); } } 2019-04-28 17:16:09.671 INFO 6915 --- [ scheduling-1] jp.smaphonia.ststodo.ScheduledTasks : The time is now 17:16:09
定期実行する間隔はプロパティファイルで設定することも可能。fixedRateではなく、fixedRateStringになっていることに注意。
@Component @Slf4j public class ScheduledTasks { @Scheduled(fixedRateString = "${scheduler.interval}") public void reportCurrentTime() { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); log.info("The time is now {}", dateFormat.format(new Date())); } }
application.properties
# スケジューラーインターバル scheduler.interval=60000
application.propertiesに出ているワーニングを解決すると、 src/main/java/META-INFOにadditional-spring-configuration-metadata.jsonが作成される。
{"properties": [{ "name": "scheduler.interval", "type": "java.lang.String", "description": "スケジューラーインターバル" }]}