定时任务
了解Cron表达式
- Cron表达式主要用来定时任务的执行,由7部分组成,中间空格隔开,中间采用空格隔开年份很少使用,所以在springBoot3.0直接砍掉了,只有6个部分,分为:秒(0-59),分,小时(0-23),日期,月份(1-12),星期(1-7;星期日开始),年份
表达式符号
*:表示任意值;例如 * * * * * ?
,:表示列表;
-:范围;例如 1-3 * * * * ? 1-3s内执行
/:间隔;0/10 * * * * ?;从0开始,每隔10s执行
?:无具体值,日期和星期可用;日期和星期其中一个为?另一个必须有值
W:从下找最接近当天的工作日,只能日期;
L:最后,日期和星期;LW可以一起用
#:第几个星期几,只能星期;例如 0 0 0 ? * 6#3,每个月第三个星期无
- Cron表达式很像正则,但不像正则那么重要,没必要背,用到即查即可,这里推荐一个网站quartz/Cron/Crontab表达式在线生成工具-BeJSON.com
springboot项目中的使用
-
启动器配置注解类@EnableScheduling开启计时器
@SpringBootApplication @EnableScheduling public class blogApplication { public static void main(String[] args) { SpringApplication.run(blogApplication.class,args); } }在定时任务类中添加@Scheduled注解
-
在定时任务方法上标注@Scheduled注解,此方法的类需要注入容器交给IOC管理
@Component public class UpdateArticleToSql { @Scheduled(cron = "0 0/10 * * * ?")//每10min执行一次 public void UpdateViewCount(){ //执行内容 } }
项目启动预处理
预处理即在springboot加载完所有的bean后立即会执行的逻辑
实现CommandLineRunner接口,重写runu方法即可,当前类需要注入容器
@Component
public class ViewRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
}
}