@Scheduled
作用:spring定時器(定時執行一次或定時輪詢執行一段代碼)
使用場景:注解在方法上
參數說明:常用參數
@Scheduled 參數說明
String cron:cron表達式定義了方法執行的時間規則
生成器工具地址-http://cron.qqe2.com/
示例
每隔5秒執行一次:*/5 * * * * ?
每隔1分鍾執行一次:0 */1 * * * ?
每天23點執行一次:0 0 23 * * ?
每天凌晨1點執行一次:0 0 1 * * ?
每月1號凌晨1點執行一次:0 0 1 1 * ?
每月最后一天23點執行一次:0 0 23 L * ?
每周星期六凌晨1點實行一次:0 0 1 ? * L
在26分、29分、33分執行一次:0 26,29,33 * * * ?
每天的0點、13點、18點、21點都執行一次:0 0 0,13,18,21 * * ?
注意事項:
1.定時器的參數有兩種寫法是用cron表達式,或者使用fixedDelay、fixedRate等參數直接配置
需要注意的是 使用cron表達式的方法,在項目首次啟動后不會直接運行,而是等到執行周期才會執行
而使用第二種方式的定時器方法,在項目啟動成功后會馬上開始執行一次,再按照時間周期執行。
測試如下:
1 @Component 2 @ConditionalOnProperty(name = "demo.task.open", havingValue = "true") 3 public class AddDataTask { 4 5 @Autowired 6 private PetShopService petShopService; 7 8 @Scheduled(cron = "0 0 17 21 * ?") 9 public void addData() { 10 11 List<PetListResponse> petList = petShopService.getPetList(new PetListRequest()); 12 13 if (!CollectionUtils.isEmpty(petList)) { 14 for (int i = 0; i < 100; i++) { 15 PetListResponse request = new PetListResponse(); 16 request.setPetName(TaskInsertUtils.getEnName()); 17 request.setPetType(PetTypeEnum.getMsgByCode(new Random().nextInt(PetTypeEnum.TYPE_RAT.getCode()))); 18 request.setPetAge(new Random().nextInt(4)); 19 request.setArriveTime(new Date()); 20 request.setIsInjection(1); 21 request.setIsAdopt(0); 22 petShopService.addPet(request); 23 System.out.println(ExceptionMsg.SUCCESS + String.valueOf(i)); 24 } 25 } 26 } 27 }