Spring Bootで定期実行する方法をご紹介します。
まずは定期実行処理を有効にするため、main処理 に @EnableScheduling を追加します。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class AmoTestExecutorApplication {
public static void main(String[] args) {
SpringApplication.run(AmoTestExecutorApplication.class, args);
}
}
そして呼び出すコンポーネントに @Scheduled を付与したメソッドを記述します。オプションを指定することで様々な定期実行をすることが出来ます。ここでは fixedRate = 5000 として、5秒間ごとに実行するよう指定しています。
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
実行すると次のようなログがコンソールに出力されるでしょう。
: The time is now 23:21:50 : The time is now 23:21:55 : The time is now 23:22:00
これで定期実行処理が完成です。
参考
@Scheduled アノテーションで定期実行 – Spring
タスクの実行とスケジューリング – Spring Framework
以上です。簡単に定期実行処理が出来ましたね。