@Scheduled 定时任务总结


@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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM