开篇
在日常的业务开发过程中,可能会需要实现一些周期性定时任务,比如定时同步数据库、定时发送短信 或者 邮件等。
那么在 Java 中,共有三种定时任务的实现方式:
通过 java.util.Timer、TimerTask 实现。
通过 Spring 自带的 SpringTask。(Spring 3.0 以后)
通过 Spring 结合 Quartz 实现。
而本文说的是第二种方式 - Spring 定时器。
使用
现在开发都是基于 springboot,而在 springboot 中配置 spring task 尤为简单。
步骤如下:
准备一个 springboot 工程
在启动类上添加 @EnableScheduling 注解 @SpringBootApplication
@EnableScheduling
public class DemoApplication {
}
在定时执行的方法上添加 @Scheduled(fixedDelay = 3 * 1000) 注解 @Scheduled(fixedDelay = 3 *1 000)
public void p1(){
System.out.println(Thread.currentThread().getName() + " p1");
}
注意: 第三步注解的属性会在后面细讲
@Scheduled 注解
在说注解属性之前, 需要了解下 Spring 定时器的三种工作模式。
fixedDelay
当上一次的任务执行完成