SpringBoot學習9.1-定時任務

1.定時任務開啓

@EnableScheduling啓用定時任務

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling // ※ 啓用定時任務
public class ScheduleConfig {
}

2.cron表達式設定定時策略

cron順序:秒 分 時 天 月 周 。
不支持年。
通配符*表示任意值,?表示不指定值,避免日期和星期的衝突
第1列秒(0~59)  
第2列分鐘0~59  
第3列小時0~23(0表示子夜)  
第4列日1~31  
第5列月1-12 或者 JAN-DEC  
第6列星期1-7 或者 SUN-SAT(1表示星期天) 

舉例:

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/** 定時任務 */
@Component // ※ 必須裝配到IoC
public class ScheduleTaskService {
	// 每5秒執行一次
	@Scheduled(fixedRate = 5000)
	public void job1() { // ※ 必須用public修飾
		System.out.println("執行job1,時刻=" + System.currentTimeMillis());
	}
	// 每10秒執行一次
	@Scheduled(fixedRate = 10000)
	@Async // 異步調用(異步線程池)
	public void job2() {
		System.out.println("執行job1,時刻=" + System.currentTimeMillis());
	}
	// 每分鐘的1秒執行
	@Scheduled(cron = "1 * * * * ?")
	public void job3() {
		System.out.println("執行job3,時刻=" + System.currentTimeMillis());
	}
	// 每天零點執行
	@Scheduled(cron = "0 0 0 * * ? ")
	public void job4() {
		System.out.println("執行job4,時刻=" + System.currentTimeMillis());
	}
	// 週五,23點30分,0秒,執行
	@Scheduled(cron = "0 30 23 ? * 6")
	public void job5() {
		System.out.println("執行job5");
	}
}

 

github:https://github.com/zhangyangfei/SpringBootLearn.git中的springTech工程。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章