在实际的项目开发工作中,我们经常会遇到需要做一些定时任务的工作,那么,在 Spring Boot 中是如何实现的呢?
代码清单:spring-boot-scheduler/pom.xml
了解源码可+VX: 445909108
Java代码
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
配置文件无需过多的配置:
代码清单:spring-boot-scheduler/src/main/resources/application.yml
Java代码
server:
port: 8080
spring:
application:
name: spring-boot-scheduler
启动主类需增加注解 @EnableScheduling 表示我们要开启定时任务这个服务。
代码清单:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/SpringBootSchedulerApplication.java
Java代码
@SpringBootApplication
@EnableScheduling
public class SpringBootSchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSchedulerApplication.class, args);
}
}
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表达式语法:
Java代码
[秒] [分] [小时] [日] [月] [周] [年]
注:[年]不是必须的域,可以省略[年],则一共6个域
Java代码 收藏代码
说明 必填 允许填写的值 允许的通配符
秒 是 0-59 , – * /
分 是 0-59 , – * /
时 是 0-23 , – * /
日 是 1-31 , – * ? / L W
月 是 1-12 / JAN-DEC , – * /
周 是 1-7 or SUN-SAT , – * ? / L #
年 否 1970-2099 , – * /
通配符说明:
4.3 参数 fixedDelay 和 fixedDelayString
这两个参数其实含义是一样的,只是一个使用的是 Long 类型,一个使用的是 String 类型。
含义都是上一次执行完毕时间点之后多长时间再执行,具体使用示例在上面的代码中已经给出。
4.4 参数 fixedRate 和 fixedRateString
这一组参数和上面的那组参数也是一样的,同样的是类型不同,含义是上一次开始执行时间点之后多长时间再执行。
4.5 参数 initialDelay 和 initialDelayString
这组参数的含义是第一次延迟多长时间后再执行。
4.6 附上 org.springframework.scheduling.annotation.Scheduled
@Scheduled 注解的使用方式其实在源码里已经讲的很清楚了,这里附上供大家参考:
Java代码
@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}.
* 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.
*
E.g. {@code "0 * * * * MON-FRI"} means once per minute on weekdays
* (at the top of the minute - the 0th second).
*
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 "";
}