Spring Boot 集成 Quartz 实现定时任务(Cron 表达式示例)
在 Spring Boot 项目中,我们经常需要定时执行某些任务,例如定期清理数据库、同步数据、发送通知等。Quartz 是一个强大的任务调度框架,可以通过 Cron 表达式实现灵活的任务调度。本文将介绍如何在 Spring Boot 中集成 Quartz 并使用 Cron 表达式进行任务调度。
1. 添加 Quartz 依赖
在 Spring Boot 项目中,首先需要引入 Quartz 相关依赖。
如果使用 Maven,在 pom.xml 中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
如果使用 Gradle,则添加:
implementation 'org.springframework.boot:spring-boot-starter-quartz'
2. 创建 Quartz 任务
在 Quartz 中,每个定时任务需要继承 org.quartz.Job 接口,并实现 execute 方法。
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.time.LocalDateTime;
public class MyQuartzJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Quartz 定时任务执行中:" + LocalDateTime.now());
}
}
3. 配置 Quartz 任务调度
Spring Boot 允许通过 SchedulerFactoryBean 配置 Quartz 任务,并使用 @Bean 方式定义任务的调度规则。
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfig {
// 定义 JobDetail
@Bean
public JobDetail {
JobBuilder.newJob(MyQuartzJob.class)
.withIdentity()
.storeDurably()
.build();
}
Trigger {
TriggerBuilder.newTrigger()
.forJob(myJobDetail())
.withIdentity()
.withSchedule(CronScheduleBuilder.cronSchedule())
.build();
}
}


