Spring Boot (十一): Spring Boot 定时任务

在实际的项目开发工作中,我们经常会遇到需要做一些定时任务的工作,那么,在 Spring Boot 中是如何实现的呢?
1. 添加依赖
在 pom.xml 文件中只需引入 spring-boot-starter 的依赖即可:
代码清单:spring-boot-scheduler/pom.xml
<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>
</dependencies>
2. 配置文件
配置文件无需过多的配置:
代码清单:spring-boot-scheduler/src/main/resources/application.yml
server:
port: 8080
spring:
application:
name: spring-boot-scheduler
3. 启动主类
启动主类需增加注解 @EnableScheduling 表示我们要开启定时任务这个服务。
代码清单:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/SpringBootSchedulerApplication.java
@SpringBootApplication
@EnableScheduling
public class SpringBootSchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSchedulerApplication.class, args);
}
}
4. 定时任务实现类
代码清单:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/task/Task.java
@Component
public class Task {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private final Logger logger = LoggerFactory.getLogger(Task.class);
/**
* cron表达式
*/
@Scheduled(cron = "*/5 * * * * ?")
private void task1() {
logger.info("task1 正在执行,现在时间:{}", dateFormat.format(new Date()));
}
/**
* 上一次开始执行时间点之后5秒再执行
*/
@Scheduled(fixedRate = 5000)
public void task2() {
logger.info("task2 正在执行,现在时间:{}", dateFormat.format(new Date()));
}
/**
* 上一次执行完毕时间点之后5秒再执行
*/
@Scheduled(fixedDelay = 5000)
public void task3() {
logger.info("task3 正在执行,现在时间:{}", dateFormat.format(new Date()));
}
/**
* 第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
*/
@Scheduled(initialDelay = 1000, fixedRate = 5000)
public void task4() {
logger.info("task4 正在执行,现在时间:{}", dateFormat.format(new Date()));
}
}
4.1 参数 cron
cron表达式语法:
[秒] [分] [小时] [日] [月] [周] [年]
注:[年]不是必须的域,可以省略[年],则一共6个域
| 说明 | 必填 | 允许填写的值 | 允许的通配符 |
|---|---|---|---|
| 秒 | 是 | 0-59 | , - * / |
| 分 | 是 | 0-59 | , - * / |
| 时 | 是 | 0-23 | , - * / |
| 日 | 是 | 1-31 | , - * ? / L W |
| 月 | 是 | 1-12 / JAN-DEC | , - * / |
| 周 | 是 | 1-7 or SUN-SAT | , - * ? / L # |
| 年 | 否 | 1970-2099 | , - * / |
通配符说明:
*表示所有值。 例如:在分的字段上设置 *,表示每一分钟都会触发。?表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 * ?-表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。,表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发/用于递增触发。如在秒上面设置”5/15” 表示从5秒开始,每增15秒触发(5,20,35,50)。 在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。L表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”W表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。#序号(表示每月的第几个周几),例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。
4.2 参数 zone
时区,接收一个java.util.TimeZone#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。
4.3 参数 fixedDelay 和 fixedDelayString
这两个参数其实含义是一样的,只是一个使用的是 Long 类型,一个使用的是 String 类型。
含义都是上一次执行完毕时间点之后多长时间再执行,具体使用示例在上面的代码中已经给出。
4.4 参数 fixedRate 和 fixedRateString
这一组参数和上面的那组参数也是一样的,同样的是类型不同,含义是上一次开始执行时间点之后多长时间再执行。
4.5 参数 initialDelay 和 initialDelayString
这组参数的含义是第一次延迟多长时间后再执行。
4.6 附上 org.springframework.scheduling.annotation.Scheduled
@Scheduled 注解的使用方式其实在源码里已经讲的很清楚了,这里附上供大家参考:
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
/**
* A special cron expression value that indicates a disabled trigger: {@value}.
* <p>This is primarily meant for use with ${...} placeholders, allowing for
* external disabling of corresponding scheduled methods.
* @since 5.1
*/
String CRON_DISABLED = "-";
/**
* A cron-like expression, extending the usual UN*X definition to include triggers
* on the second as well as minute, hour, day of month, month and day of week.
* <p>E.g. {@code "0 * * * * MON-FRI"} means once per minute on weekdays
* (at the top of the minute - the 0th second).
* <p>The special value {@link #CRON_DISABLED "-"} indicates a disabled cron trigger,
* primarily meant for externally specified values resolved by a ${...} placeholder.
* @return an expression that can be parsed to a cron schedule
* @see org.springframework.scheduling.support.CronSequenceGenerator
*/
String cron() default "";
/**
* A time zone for which the cron expression will be resolved. By default, this
* attribute is the empty String (i.e. the server's local time zone will be used).
* @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},
* or an empty String to indicate the server's default time zone
* @since 4.0
* @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
* @see java.util.TimeZone
*/
String zone() default "";
/**
* Execute the annotated method with a fixed period in milliseconds between the
* end of the last invocation and the start of the next.
* @return the delay in milliseconds
*/
long fixedDelay() default -1;
/**
* Execute the annotated method with a fixed period in milliseconds between the
* end of the last invocation and the start of the next.
* @return the delay in milliseconds as a String value, e.g. a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
*/
String fixedDelayString() default "";
/**
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return the period in milliseconds
*/
long fixedRate() default -1;
/**
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return the period in milliseconds as a String value, e.g. a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
*/
String fixedRateString() default "";
/**
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate()} or {@link #fixedDelay()} task.
* @return the initial delay in milliseconds
* @since 3.2
*/
long initialDelay() default -1;
/**
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate()} or {@link #fixedDelay()} task.
* @return the initial delay in milliseconds as a String value, e.g. a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
*/
String initialDelayString() default "";
}
5. 示例代码
6. 参考
https://www.jianshu.com/p/1defb0f22ed1
Spring Boot (十一): Spring Boot 定时任务的更多相关文章
- Spring学习(十一)-----Spring使用@Required注解依赖检查
Spring学习(九)-----Spring依赖检查 bean 配置文件用于确定的特定类型(基本,集合或对象)的所有属性被设置.在大多数情况下,你只需要确保特定属性已经设置但不是所有属性.. 对于这种 ...
- spring boot注解之@Scheduled定时任务实现
java实现定时任务一般使用timer,或者使用quartz组件.现在在spring boot提供了更加方便的实现方式. spring boot已经集成了定时任务.使用@Secheduled注解. @ ...
- Spring Boot集成quartz实现定时任务并支持切换任务数据源
org.quartz实现定时任务并自定义切换任务数据源 在工作中经常会需要使用到定时任务处理各种周期性的任务,org.quartz是处理此类定时任务的一个优秀框架.随着项目一点点推进,此时我们并不满足 ...
- SpringBoot(十一): Spring Boot集成Redis
1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...
- Spring Kafka和Spring Boot整合实现消息发送与消费简单案例
本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...
- Spring Kafka整合Spring Boot创建生产者客户端案例
每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 创建一个kafka-producer-master的maven工程.整个项目结构如下: ...
- Spring Boot,Spring Cloud,Eureka,Actuator,Spring Boot Admin,Stream,Hystrix
Spring Boot,Spring Cloud,Eureka,Actuator,Spring Boot Admin,Stream,Hystrix 一.Spring Cloud 之 Eureka. 1 ...
- 一:Spring Boot、Spring Cloud
上次写了一篇文章叫Spring Cloud在国内中小型公司能用起来吗?介绍了Spring Cloud是否能在中小公司使用起来,这篇文章是它的姊妹篇.其实我们在这条路上已经走了一年多,从16年初到现在. ...
- 使用Spring Session实现Spring Boot水平扩展
小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...
- 一起来学spring Cloud | 第一章:spring Cloud 与Spring Boot
目前大家都在说微服务,其实微服务不是一个名字,是一个架构的概念,大家现在使用的基于RPC框架(dubbo.thrift等)架构其实也能算作一种微服务架构. 目前越来越多的公司开始使用微服务架构,所以在 ...
随机推荐
- codeforces 389 D. Fox and Minimal path(构造+思维)
题目链接:https://vjudge.net/contest/175446#problem/J 题解:显然要用最多n个点构成的图要使的得到的最短路条数有1e9次个,显然要有几个数相乘容易想到2的几进 ...
- 背包形动态规划 fjutoj2347 采药
采药 TimeLimit:1000MS MemoryLimit:128MB 64-bit integer IO format:%lld Problem Description 辰辰是个天资聪颖的 ...
- win10 无法安装/启用 .net framework 3.5
有些程序依赖.net framework 3.5 win10可以在控制面板->程序和功能->启用或关闭windows功能 启用 但有时会报错 比如 0x800f0950 官方论坛的解决办法 ...
- JSP内置对象(一)
一.out对象out对象是JspWriter类的实例,是向客户端输出内容常用的对象1.void println() out的println()方法,向客户端打印字符串 2. void clear() ...
- Java内部类的使用小结 形参为什么要用final
部类是指在一个外部类的内部再定义一个类.类名不需要和文件夹相同. *内部类可以是静态static的,也可用public,default,protected和private修饰.(而外部顶级类即类名和文 ...
- Python 为了提升性能,竟运用了共享经济
大家或许知道,Python 为了提高内存的利用效率,采用了一套共用对象内存的分配策略. 例如,对于那些数值较小的数字对象([-5, 256]).布尔值对象.None 对象.较短的字符串对象(通常 是 ...
- spring boot使用AOP切面编程
spring boot使用AOP 1.在pom文件中添加依赖: <!--spring boot aop切面--> <dependency> <groupId>org ...
- Fortify安全漏洞一般处理方法
前段时间公司又一轮安全审查,要求对各项目进行安全扫描,排查漏洞并修复,手上有几个历史项目,要求在限定的时间内全部修复并提交安全报告,也不清楚之前是如何做的漏洞修复,这次使用工具扫描出来平均每个项目都还 ...
- Log4Net 日志记录的实现
一.前言 在上一篇文章[(转载)非常完善的Log4net配置详细说明]介绍了Log4Net的配置说明,如果不知道的可以去看看,这里我们就介绍一下日志记录的实现,说得都比较基础,所以大神请绕过. 二.L ...
- 个人IP「Android大强哥」上线啦!
自从入职新公司之后就一直忙得不行,一边熟悉开发的流程,一边熟悉各种网站工具的使用,一边又在熟悉业务代码,好长时间都没有更文了. 不过新公司的 mentor(导师)还是很不错的,教给我很多东西,让我也能 ...