Spring Boot 3.4.3 整合 Quartz 定时任务
在企业级应用开发中,定时任务是实现自动化流程的重要工具,例如定时清理日志、发送通知或执行数据同步等。Spring Boot 3.4.3 提供了内置的调度支持,而 Quartz 作为一款功能强大的任务调度框架,可以轻松集成到 Spring Boot 中,实现灵活的定时任务管理。本文将详细介绍如何在 Spring Boot 3.4.3 中整合 Quartz,创建和管理定时任务,并附上完整代码示例,助你在2025年的项目中快速实现定时任务功能。
1. Quartz 简介
1.1 什么是 Quartz?
Quartz 是一个功能丰富的开源任务调度框架,支持从简单定时任务到复杂 Cron 表达式的调度需求。它通过 Job(任务)、Trigger(触发器)和 Scheduler(调度器)三大核心组件,提供强大的任务管理能力。
1.2 Quartz 的优点
- 灵活性:支持多种触发器类型(如 SimpleTrigger 和 CronTrigger)。
- 可扩展性:支持内存或数据库存储任务。
- 易集成:与 Spring Boot 无缝对接。
- 高可用性:支持集群部署。
1.3 本文目标
- 配置 Quartz 基本环境。
- 实现简单定时任务。
- 提供动态添加和删除任务的接口。
2. 项目实战
以下是基于 Spring Boot 3.4.3 整合 Quartz 的完整步骤。
2.1 添加 Maven 依赖
在 pom.xml
中添加必要的依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.3</version>
</parent>
<groupId>cn.itbeien</groupId>
<artifactId>springboot-quartz</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Quartz -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
</dependencies>
</project>
说明:
spring-boot-starter-quartz
:Quartz 与 Spring Boot 的集成依赖。
2.2 配置 Quartz
在 application.yml
中进行基本配置(可选,默认使用内存存储):
spring:
quartz:
job-store-type: memory # 使用内存存储任务
properties:
org:
quartz:
scheduler:
instanceName: MyScheduler
instanceId: AUTO
threadPool:
threadCount: 5 # 线程池大小
说明:
job-store-type: memory
:默认使用内存存储,适合简单场景。- 可选配置数据库存储(参考后续进阶功能)。
2.3 创建 Quartz Job
定义一个简单的定时任务:
package cn.joyous.job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.time.LocalDateTime;
public class SimpleJob extends QuartzJobBean {
private static final Logger logger = LoggerFactory.getLogger(SimpleJob.class);
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
logger.info("定时任务执行中,当前时间:{}", LocalDateTime.now());
}
}
代码说明:
QuartzJobBean
:Quartz 提供的基类,用于定义任务逻辑。executeInternal
:任务的具体执行内容。
2.4 配置 Job 和 Trigger
创建一个配置类,定义任务和触发器:
package cn.joyous.config;
import cn.joyous.job.SimpleJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfig {
@Bean
public JobDetail simpleJobDetail() {
return JobBuilder.newJob(SimpleJob.class)
.withIdentity("simpleJob")
.storeDurably()
.build();
}
@Bean
public Trigger simpleJobTrigger() {
return TriggerBuilder.newTrigger()
.forJob(simpleJobDetail())
.withIdentity("simpleTrigger")
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5) // 每5秒执行一次
.repeatForever())
.build();
}
}
代码说明:
JobDetail
:定义任务的身份和类。Trigger
:设置触发规则,这里使用简单调度(每 5 秒执行)。
2.5 创建控制器管理任务
提供 RESTful 接口动态管理任务:
package cn.joyous.controller;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class QuartzController {
@Autowired
private Scheduler scheduler;
@PostMapping("/job")
public String addJob(@RequestParam String jobName, @RequestParam int interval) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class)
.withIdentity(jobName)
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(jobName + "Trigger")
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(interval)
.repeatForever())
.build();
scheduler.scheduleJob(jobDetail, trigger);
return "任务添加成功";
}
@DeleteMapping("/job/{jobName}")
public String deleteJob(@PathVariable String jobName) throws SchedulerException {
scheduler.deleteJob(new JobKey(jobName));
return "任务删除成功";
}
}
2.6 启动与测试
- 启动 Spring Boot 应用。
- 检查日志,每 5 秒输出一次任务执行信息。
- 测试接口:
- 添加任务:
POST http://localhost:8080/api/job?jobName=testJob&interval=10
- 删除任务:
DELETE http://localhost:8080/api/job/testJob
- 添加任务:
3. 进阶功能(可选)
-
使用 Cron 表达式
修改触发器为 Cron 调度:@Bean public Trigger simpleJobTrigger() { return TriggerBuilder.newTrigger() .forJob(simpleJobDetail()) .withIdentity("simpleTrigger") .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?")) // 每10秒执行 .build(); }
-
数据库存储
添加 MySQL 支持(参考上一篇文章):spring: datasource: url: jdbc:mysql://localhost:3306/quartz_db?useSSL=false&serverTimezone=UTC username: root password: 123456 quartz: job-store-type: jdbc
-
任务参数传递
为 Job 添加数据:JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class) .usingJobData("key", "value") .build(); // 在 Job 中获取 String value = context.getJobDetail().getJobDataMap().getString("key");
4. 总结
Spring Boot 3.4.3 整合 Quartz 为定时任务提供了简单而强大的实现方式。本文从基础配置到任务管理接口,覆盖了实际开发中的核心需求。相比 Spring 的 @Scheduled
,Quartz 在灵活性和扩展性上更胜一筹,适合复杂调度场景。