SpringBoot自動任務——使用Spring自帶@Scheduled

參考網址

https://www.tianmaying.com/tutorial/spring-scheduling-taskjava

要點1--定時任務上加@Scheduled註解(類上加@Component註解)

自動任務方法上加@Scheduled註解,註解後面加定時任務的定時。spring

/**
 * 
 * Description:定時任務示例
 *
 */
@Component
public class ScheduledTask {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Integer count0 = 1;
    private Integer count1 = 1;
    private Integer count2 = 1;

    /**
     * 
     * Description:表示每隔5000ms,Spring scheduling會調用一次該方法,不論該方法的執行時間是多少
     * @throws InterruptedException
     */
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() throws InterruptedException {
        System.out.println(String.format("---第%s次執行,當前時間爲:%s", count0++, dateFormat.format(new Date())));
    }

    /**
     * 
     * Description:表示當方法執行完畢5000ms後,Spring scheduling會再次調用該方法
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTimeAfterSleep() throws InterruptedException {
        System.out.println(String.format("===第%s次執行,當前時間爲:%s", count1++, dateFormat.format(new Date())));
    }

    //一種通用的定時任務表達式,這裏表示每隔5秒執行一次
    @Scheduled(cron = "*/5 * * * * * *")
    public void reportCurrentTimeCron() throws InterruptedException {
        System.out.println(String.format("+++第%s次執行,當前時間爲:%s", count2++, dateFormat.format(new Date())));
    }

}

要點2--幾種定時的表示方法

在@Scheduled註解中,咱們使用了三種方式來實現了同一個功能:每隔5秒鐘記錄一次當前的時間:app

fixedRate = 5000表示每隔5000ms,Spring scheduling會調用一次該方法,不論該方法的執行時間是多少。ui

fixedDelay = 5000表示當方法執行完畢5000ms後,Spring scheduling會再次調用該方法。spa

cron = "*/5 * * * * * *"提供了一種通用的定時任務表達式,這裏表示每隔5秒執行一次。code

要點3--main方法上加@EnableScheduling註解

main上加@EnableScheduling註解,說明要開啓SpringBoot的自動任務。orm

@EnableScheduling 註解的做用是發現註解@Scheduled的任務並後臺執行。ip

@RestController
@SpringBootApplication(exclude = SpringDataWebAutoConfiguration.class)
@EnableScheduling
public class RuicheServerJSP {
	
	@RequestMapping("/")
	String index(){
		return "Hello Spring Boot";
	}

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

★@Scheduled中cron一些經常使用的表達式

"0 0 12 * * ?"    天天中午十二點觸發 get

"0 15 10 ? * *"    天天早上10:15觸發 io

"0 15 10 * * ?"    天天早上10:15觸發

"0 15 10 * * ? *"    天天早上10:15觸發 

相關文章
相關標籤/搜索