定時任務
記錄自己學習SpringBoot的時候,運用到的定時任務筆記
首先是SpringBoot的主函數入口,最主要的是@EnableScheduling註解
@EnableScheduling//讓定時任務自動配置的註解
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Service層編寫定時任務,最主要的是@Scheduled註解中的cron=" "的時間安排
/**
* @author YESIJIE
* @date 2019-11-29 15:42
*/
@Service
public class ScheduledService {
//@Scheduled(cron = "2 * * * * MON-SAT")//每分鐘的第兩秒打印一次
//@Scheduled(cron = "1,2,3,4 * * * * MON-SAT")//每分鐘的第1-4秒打印一次
//@Scheduled(cron = "1-4 * * * * MON-SAT")//每分鐘的第1-4秒打印一次
@Scheduled(cron = "0/4 * * * * MON-SAT")//每4秒打印一次
public void ScheduledOne(){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("每兩秒打印一次-----"+simpleDateFormat.format(new Date()));
}
}
控制檯顯示,每四秒執行一次
每兩秒打印一次——2019-11-29 03:55:44
每兩秒打印一次——2019-11-29 03:55:48
每兩秒打印一次——2019-11-29 03:55:52
每兩秒打印一次——2019-11-29 03:55:56