SpringBoot非官方教程 | 第十八篇: 定时任务(Scheduling Tasks)
来源:互联网 发布:php是最好的编程语言 编辑:程序博客网 时间:2024/05/17 08:37
转载请标明出处:
http://blog.csdn.net/forezp/article/details/71023783
本文出自方志朋的博客
这篇文章将介绍怎么通过spring去做调度任务。
构建工程
创建一个Springboot工程,在它的程序入口加上@EnableScheduling,开启调度任务。
@SpringBootApplication@EnableSchedulingpublic class SpringbootSchedulingTasksApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSchedulingTasksApplication.class, args); }}
创建定时任务
创建一个定时任务,每过5s在控制台打印当前时间。
@Componentpublic class ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); }}
通过在方法上加@Scheduled注解,表明该方法是一个调度任务。
- @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
- @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
- @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
- @Scheduled(cron=” /5 “) :通过cron表达式定义规则,什么是cro表达式,自行搜索引擎。
测试
启动springboot工程,控制台没过5s就打印出了当前的时间。
2017-04-29 17:39:37.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:37
2017-04-29 17:39:42.671 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:42
2017-04-29 17:39:47.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:47
2017-04-29 17:39:52.675 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:52
总结
在springboot创建定时任务比较简单,只需2步:
- 1.在程序的入口加上@EnableScheduling注解。
- 2.在定时方法上加@Scheduled注解。
参考资料
https://spring.io/guides/gs/scheduling-tasks/
源码下载
https://github.com/forezp/SpringBootLearning
优秀文章推荐:
- 更多springboot 教程:springBoot非官方教程 | 文章汇总
- 更多springcoud 教程:史上最简单的 SpringCloud 教程 | 文章汇总
- SpringBoot非官方教程 | 第十八篇: 定时任务(Scheduling Tasks)
- SpringBoot非官方教程 | 第十八篇: 定时任务(Scheduling Tasks)
- SpringBoot非官方教程 | 第十八篇: 定时任务(Scheduling Tasks)
- SpringBoot非官方教程 | 第十八篇: 定时任务(Scheduling Tasks)
- Scheduling Tasks定时任务
- Spring Boot 之 Scheduling Tasks定时任务
- SpringBoot之Scheduling Tasks
- Spring任务调度Scheduling Tasks
- spring - Scheduling Tasks 计划任务
- Spring任务调度Scheduling Tasks
- springboot开启定时任务教程
- SpringBoot非官方教程 | 第十七篇:上传文件
- SpringBoot非官方教程 | 第二十三篇: 异步方法
- SpringBoot非官方教程 | 第十七篇:上传文件
- SpringBoot非官方教程 | 第二十三篇: 异步方法
- SpringBoot非官方教程 | 第十七篇:上传文件
- SpringBoot非官方教程 | 第二十三篇: 异步方法
- SpringBoot非官方教程 | 第十七篇:上传文件
- C++11中的std::call_once
- Android 中基本界面布局
- 康托展开&逆康托展开
- poj1631(最长上升子序列 nlogn)
- LeetCode Weekly Contest 30解题思路
- SpringBoot非官方教程 | 第十八篇: 定时任务(Scheduling Tasks)
- 汇编bne的问题 汇编中的标号1: 以及bne 1b解释
- 【pygame入门】-- 字体
- 米磊博士:下一个风口就是硬科技,抓住机遇,中国能重返世界之巅
- Comet[翻译]
- 我的java学习路之选择和循环
- 好用的chrome插件:鼠标手势、阅读视图、onetab
- linux CLK时钟驱动
- 位图 BitMap