場景:
在開發中,遇到讓做定時任務很常見,而相比於傳統框架,springboot中寫定時任務顯得格外的簡單。
思路:2步走;
第一,開啓springboot的定時任務功能,這個只需在入口文件類上加上註釋 @EnableScheduling
@EnableAsync //開啓異步註解功能
@EnableScheduling//開啓定時功能的註解
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
第二:在自己的接口方法上,使用定時器註解 @Scheduled (cron = "0 * * * * 0-7 ")
@Service
public class ScheduledService {
/**
* 定時任務測試,在每分鐘的第0秒執行任務
*/
@Scheduled(cron = "0 * * * * 0-7 ")
public void hello(){
System.out.println("定時任務執行。。。。");
}
}
注意:
這裏要說明的是定時器註解後的CRON語法,這個自己查下網上的說明即可,其後的6個位置,從左到右依次代表 “秒 分 時 日 月 周”