(转)Springboot定时任务
在我们的项目开发过程中,经常需要定时任务来帮助我们来做一些内容,springboot默认已经帮我们实行了,只需要添加相应的注解就可以实现
1、pom包配置
pom包里面只需要引入springboot starter包即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional> true </optional> </dependency> </dependencies> |
2、启动类启用定时
在启动类上面加上@EnableScheduling
即可开启定时
1 2 3 4 5 6 7 8 | @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application. class , args); } } |
3、创建定时任务实现类
定时任务1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | @Component public class SchedulerTask { private int count= 0 ; @Scheduled (cron= "*/6 * * * * ?" ) private void process(){ System.out.println( "this is scheduler task runing " +(count++)); } } 定时任务 2 : @Component public class Scheduler2Task { private static final SimpleDateFormat dateFormat = new SimpleDateFormat( "HH:mm:ss" ); @Scheduled (fixedRate = 6000 ) public void reportCurrentTime() { System.out.println( "现在时间:" + dateFormat.format( new Date())); } } |
结果如下:
1 2 3 4 5 6 7 8 | this is scheduler task runing 0 现在时间: 09 : 44 : 17 this is scheduler task runing 1 现在时间: 09 : 44 : 23 this is scheduler task runing 2 现在时间: 09 : 44 : 29 this is scheduler task runing 3 现在时间: 09 : 44 : 35 |
参数说明
@Scheduled
参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?"
,一种是 fixedRate = 6000
,两种都表示每隔六秒打印一下内容。
fixedRate 说明
@Scheduled(fixedRate = 6000)
:上一次开始执行时间点之后6秒再执行 PS:经测试,如果定时任务执行时间小于6s,则每6秒执行一次;如果定时任务代码块执行时间超过6s,则定时任务执行完之后会立马调用。@Scheduled(fixedDelay = 6000)
:上一次执行完毕时间点之后6秒再执行 PS: 相当于调度器@Scheduled(initialDelay=1000, fixedRate=6000)
:第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次
转自:http://www.ityouknow.com/springboot/2016/12/02/spring-boot-scheduler.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2014-09-21 HDU1010:Tempter of the Bone(dfs+剪枝)