eclipse中搭建springboot學習(13)---定時任務
啟動類
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@ServletComponentScan//啟用定時任務
@EnableScheduling
public class DemoApplication {public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}}
定時任務類
package com.example.demo1101;
import java.text.SimpleDateFormat;
import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;/*
* fixedRate 說明
*
* @Scheduled(fixedRate = 6000) :上一次開始執行時間點之後6秒再執行
*
* @Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之後6秒再執行
*
* @Scheduled(initialDelay=1000, fixedRate=6000)
* :第一次延遲1秒後執行,之後按fixedRate的規則每6秒執行一次
*
*/@Component
public class ScheduleTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private int count = 0;
// @Scheduled 引數可以接受兩種定時的設定,一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate =
// 6000,兩種都表示每隔六秒列印一下內容// 間隔六秒列印一次count
@Scheduled(cron = "*/6 * * * * ?")
public void run() {
System.out.println(count++);
}// 間隔六秒列印一次時間
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("現在時間:" + dateFormat.format(new Date()));
}}