12.Springboot 之 使用Scheduled做定时任务
来源:互联网 发布:什么软件可以升级win10 编辑:程序博客网 时间:2024/06/08 13:30
本文所属【知识林】:http://www.zslin.com/web/article/detail/21
在定时任务中一般有两种情况:
- 指定何时执行任务
- 指定多长时间后执行任务
这两种情况在Springboot中使用Scheduled都比较简单的就能实现了。
- 修改程序入口
@SpringBootApplication@EnableSchedulingpublic class RootApplication { public static void main(String [] args) { SpringApplication.run(RootApplication.class, args); }}
在程序入口的类上加上注释@EnableScheduling
即可开启定时任务。
- 编写定时任务类
@Componentpublic class MyTimer { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 3000) public void timerRate() { System.out.println(sdf.format(new Date())); }}
在程序启动后控制台将每隔3秒输入一次当前时间,如:
23:08:4823:08:5123:08:54
注意: 需要在定时任务的类上加上注释:@Component
,在具体的定时任务方法上加上注释@Scheduled
即可启动该定时任务。
下面描述下@Scheduled
中的参数:
@Scheduled(fixedRate=3000)
:上一次开始执行时间点后3秒
再次执行;
@Scheduled(fixedDelay=3000)
:上一次执行完毕时间点后3秒
再次执行;
@Scheduled(initialDelay=1000, fixedDelay=3000)
:第一次延迟1秒
执行,然后在上一次执行完毕时间点后3秒
再次执行;
@Scheduled(cron="* * * * * ?")
:按cron
规则执行。
下面贴出完整的例子:
package com.zslin.timers;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.Date;/** * Created by 钟述林 393156105@qq.com on 2016/10/22 21:53. */@Componentpublic class MyTimer { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); //每3秒执行一次 @Scheduled(fixedRate = 3000) public void timerRate() { System.out.println(sdf.format(new Date())); } //第一次延迟1秒执行,当执行完后3秒再执行 @Scheduled(initialDelay = 1000, fixedDelay = 3000) public void timerInit() { System.out.println("init : "+sdf.format(new Date())); } //每天23点27分50秒时执行 @Scheduled(cron = "50 27 23 * * ?") public void timerCron() { System.out.println("current time : "+ sdf.format(new Date())); }}
在Springboot中使用Scheduled来做定时任务比较简单,希望这个例子能有所帮助!
0 0
- Springboot 之 使用Scheduled做定时任务
- Springboot之使用Scheduled做定时任务
- 12.Springboot 之 使用Scheduled做定时任务
- SpringBoot 使用Scheduled 定时任务入门
- SpringBoot 定时任务@Scheduled详解
- springboot【25】定时任务@Scheduled
- SpringBoot定时任务(@Scheduled)说明
- 集群服务器下使用SpringBoot @Scheduled注解定时任务
- spring @Scheduled 定时任务使用
- springboot定时任务使用
- Spring 定时任务之 @Scheduled cron表达式
- Spring 定时任务之 @Scheduled cron表达式
- Spring 定时任务之 @Scheduled cron表达式
- Spring 定时任务之 @Scheduled cron表达式
- Spring 定时任务之 @Scheduled cron表达式
- Spring 定时任务之 @Scheduled cron表达式
- Spring 定时任务之 @Scheduled cron表达式
- Spring 定时任务之 @Scheduled cron表达式
- C++ 虚继承派生类构造函数的写法
- 【堆】堆排序
- 在JAVAWEB项目中用JSP生成数据库数据曲线图
- 文章标题
- Oracle数据库中计算时间差的常用表达式
- 12.Springboot 之 使用Scheduled做定时任务
- Mac下AndroidStudio中手动配置Gradle
- OpenCV: OpenCV人脸检测框可信度排序
- Feign和Hystrix异常熔断的理解
- bzoj2428 [HAOI2006]均分数据
- 编程必备数学知识汇总
- python3的文件读写模式
- 关于iphone 上touch事件动态改变元素位置时与touch点发生偏移的问题
- Struts校验