springboot-定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,spring为我们提供了异步执行任务调度的方式,提供了两个接口
- TaskExecutor接口
- TaskScheduler接口
两个注解:
- @EnableScheduling
- @Scheduled
1 创建一个springboot项目
创建项目过程中添加web模块
2 在主程序上开启定时任务功能
只需要增加一个@EnableScheduling注解
src/main/java/com/lv/Springboot09TestApplication.java
package com.lv; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling //开启定时功能的注解 @SpringBootApplication public class Springboot09TestApplication { public static void main(String[] args) { SpringApplication.run(Springboot09TestApplication.class, args); } }
3 新建一个service包,并在该包下编写ScheduledService
使用cron表达式设定时间
src/main/java/com/lv/service/ScheduledService.java
package com.lv.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class ScheduledService { //在一个特定的时间执行这个方法~ Timer //cron表达式~ //秒 分 时 日 月 周几 /* 30 15 10 * * ? 每天10点15分30 执行一次 30 0/5 10,18 * * ? 每天10点和18点,每个5分钟执行一次 0 15 10 ? * 1-6 每个月的周一到周六 10:15分执行一次 */ @Scheduled(cron = "0 46 16 * * ?") public void hello(){ System.out.println("hello,你被执行了~"); } }
4 启动程序测试
方法在我们设定的时间准时执行
5 cron
cron表达式在线生成地址: quartz/Cron/Crontab表达式在线生成工具-BeJSON.com
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?