一、背景介绍
在实际的业务开发过程中,我们经常会需要定时任务来帮助我们完成一些工作,例如每天早上 6 点生成销售报表、每晚 23 点清理脏数据等等。
如果你当前使用的是 SpringBoot 来开发项目,那么完成这些任务会非常容易!
SpringBoot 默认已经帮我们完成了相关定时任务组件的配置,我们只需要添加相应的注解@Scheduled
就可以实现任务调度!
二、方案实践
2.1、pom 包配置
pom
包里面只需要引入Spring Boot Starter
包即可!
<dependencies>
<!--spring boot核心-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--spring boot 测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.2、启动类启用定时调度
在启动类上面加上@EnableScheduling
即可开启定时
@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class, args);
}
}
2.3、创建定时任务
Spring Scheduler
支持四种形式的任务调度!
- fixedRate:固定速率执行,例如每5秒执行一次
- fixedDelay:固定延迟执行,例如距离上一次调用成功后2秒执行
- initialDelay:初始延迟任务,例如任务开启过5秒后再执行,之后以固定频率或者间隔执行
- cron:使用 Cron 表达式执行定时任务
2.3.1、固定速率执行
你可以通过使用fixedRate
参数以固定时间间隔来执行任务,示例如下:
@Component
public class SchedulerTask {
private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-