spring boot 学习(八)定时任务 @Scheduled
2017-01-28 17:50
766 查看
SpringBoot 定时任务 @Scheduled
前言
有时候,我们有这样的需求,需要在每天的某个固定时间或者每隔一段时间让应用去执行某一个任务。一般情况下,可以使用多线程来实现这个功能;在 Spring 框架下可以搭配 Quartz 来实现,附上笔记 Spring Quartz 实现多任务定时调用。在 SpringBoot 框架下,我们可以用 Spring scheduling 来实现定时任务功能。首先,我们先创建一个 Spring Boot 项目。创建方法:
* (自动完成初始化)http://blog.csdn.net/u011244202/article/details/54767036
* (手动完成初始化)http://blog.csdn.net/u011244202/article/details/54604421
同时要注意,SpringBoot 项目需要 JDK8 的编译环境!
然后,在项目主类中加入
@EnableScheduling注解,启用定时任务的配置
@SpringBootApplication @EnableScheduling public class Application extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
最后,创建定时任务实现类,注意加上注解
@Scheduled
@Scheduled 的介绍
1. cron 表达式与 zone
zone:表示将解析cron表达式的时区。关于 cron 表达式,可以参考一下 http://blog.csdn.net/u011244202/article/details/54382466 里面的附录。
2. fixedRate 的解释
调用固定周期(以毫秒为单位)执行方法。就是上一次开始执行时间点之后延迟执行。3. fixedDelay 的解释
上次调用结束和下一次调用结束之间的固定周期(以毫秒为单位)执行方法。就是上一次执行完毕时间点之后延迟执行。4. initialDelay 的解释
在第一次执行fixedRate()或fixedDelay()任务之前延迟(以毫秒为单位)。实例
在项目启动 8s 后,每隔 5s 调用定时任务。@Component public class ScheduledTasks { //输出时间格式 private static final SimpleDateFormat format = new SimpleDateFormat("HH(hh):mm:ss S"); @Scheduled(initialDelay = 5000, fixedRate = 5000) public void firstScheduledTasks(){ System.out.println("定时任务执行,现在时间是 : "+format.format(new Date())); } }
结果图:
项目参考地址
项目参考地址 : https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B4注意:
cron、fixedDelay、fixedRate 三者之间不能共存!!!会抛出一个错误:
Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'firstScheduledTasks': Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required.
官方文档
实例文档 : http://spring.io/guides/gs/scheduling-tasks/注解文档 : http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html
相关文章推荐
- spring-boot 使用@Scheduled 开启定时任务
- 在Spring Boot中使用@Scheduled实现定时任务
- SpringBoot使用@Scheduled创建定时任务
- 从0开始学习SpringCould(3)--SpringBoot 定时任务
- spring-boot实战【09】【转】:Spring Boot中使用@Scheduled创建定时任务
- SpringBoot学习(九)--SpringBoot定时任务@Scheduled和动态定时任务
- Spring Boot中使用@Scheduled创建定时任务
- Spring Boot中使用@Scheduled创建定时任务
- Spring Boot学习进阶笔记(五)-添加定时任务
- SpringBoot学习-持久化Quartz定时任务管理
- 在Spring Boot中使用@Scheduled实现定时任务
- Spring Boot 定时调度任务 @Scheduled
- 在Spring Boot中使用@Scheduled实现定时任务
- 在Spring Boot中使用@Scheduled实现定时任务
- Spring Boot中使用@Scheduled创建定时任务
- 使用 Spring-boot 的 @Scheduled 来完成一个定时任务
- spring-boot通过@Scheduled配置定时任务及定时任务@Scheduled注解的方法
- Spring Boot中使用@Scheduled创建定时任务
- 详解Spring Boot中使用@Scheduled创建定时任务
- Spring Boot 学习15--定时任务的使用