Springboot定时任务

开启定时任务注解
设置执行时间
【阿里云短信接口、调用大模型接口】
1、开启定时任务注解:
在启动类添加注解@EnableScheduling
2、@Scheduled:设置时间(固定时间间隔)
demo1:
@EnableScheduling @SpringBootApplication public class DingshiApplication { public static void main(String[] args) { SpringApplication.run(DingshiApplication.class, args); } //下面的两个方法在第一次启动项目的时候会执行一次 // 半小时提醒一次 @Scheduled(fixedRate = 30*60*1000) public void playSth1(){ System.out.println("任务一"+ DateFormat.getDateInstance().format(new Date())); } // 四小时执行一次 @Scheduled(fixedRate = 4*60*60*1000) public void playSth2(){ System.out.println("任务二"+ DateFormat.getDateInstance().format(new Date())); } }
cron表达式:
Cron 表达式是一种用于指定定时任务执行时间的字符串表达式。它由 6 个字段组成,分别表示秒、分钟、小时、天数、月份和星期几。每个字段都可以使用特定的符号来指定时间范围或间隔。
通用符号:, * - /
  • , :表示列出枚举值。例如:在 分钟 域使用5,20,表示在时间的分钟数为5,20时触发事件。
  • - :表示范围:例如在 分钟 域使用5-20,表示在时间的分钟数为5到20时每分钟都触发事件
  • * :表示匹配该域的任意值。假如在 分钟 域使用*,表示时间分钟数不做限制,分分钟都出发事件
  • / :表示起始时间开始触发,然后每个固定时间触发一次。例如在 分钟 域使用5/20,表示事件的分钟数为5时触发一次,后隔20分钟即25,45再分别触发一次。
spring中只可以使用6位。
0 0 2 1 * ?:每月一号凌晨两点触发。
0 10,44 14 ? 3 WED :3月的每个星期3下午两点10分和44分时触发
专有符号:
  • ?:只能用在DayofMonth和DayofWeek两个域,由于DayOfMonth和DayOfWeek互斥,需对其一进行设置。
  • L:表示最后,只能出现在DayofWeek和DayofMonth域。如果在DayofWeek域使用5L,意味着在最后一个星期四触发。
  • W:表示有效工作日(周一到周五),只能出现在DayofMoneth域,系统将在离指定日期的最近的有效工作日触发事件。
  • #:用于确定每个月第几个星期几,只能出现在DayofWeek域。例如在4#2,表示某月的第二个星期三
  • C:只能用在DayofMonth和DayofWeek两个域,需要关联日历,如果没关联可以忽略
转有符号:
  • 专有符号中除了?外,再Spring定时任务中都不支持。

spring异步多线程实现:

开启异步注解
设置异步执行
demo2:
@EnableAsync @EnableScheduling @SpringBootApplication public class DingshiApplication { public static void main(String[] args) { SpringApplication.run(DingshiApplication.class, args); } //下面的两个方法在第一次启动项目的时候会执行一次 @Async @Scheduled(fixedRate = 5*1000) public void playSth1(){ System.out.println("任务1线程:"+Thread.currentThread().getName()); System.out.println("任务一"+ DateFormat.getDateInstance().format(new Date())); } @Async @Scheduled(cron = "0 0 2 1 * ? ") @Scheduled(fixedRate = 10*1000) public void playSth2(){ System.out.println("任务2线程:"+Thread.currentThread().getName()); System.out.println("任务二"+ DateFormat.getDateInstance().format(new Date())); } }

总结:

1、通过@EnableScheduling注解开启定时任务
2、通过@Scheduled设置任务执行时间
3、cron表达式讲解
4、通过@EnableAsync开启异步执行
5、通过@Async设置异步执行的方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值