1. 程式人生 > >Spring Boot學習進階筆記(五)-添加定時任務

Spring Boot學習進階筆記(五)-添加定時任務

imp 配置 ren 時間 report rate enable lin enables

一、在Spring [email protected],啟用定時任務的配置。
@SpringBootApplication
@EnableScheduling
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

二、創建定時任務,每隔5秒打印一下當前時間
@Component
public class ScheduledTasks {

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("現在時間:" + dateFormat.format(new Date()));
}

}

@Scheduled詳解

[email protected]
@Scheduled(fixedRate = 5000) :上一次開始執行時間點之後5秒再執行
@Scheduled(fixedDelay = 5000) :上一次執行完畢時間點之後5秒再執行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次
@Scheduled(cron="*/5 * * * * *") :通過cron表達式定義規則

詳細介紹:http://spring.io/guides/gs/scheduling-tasks/

Spring Boot學習進階筆記(五)-添加定時任務