ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

SpringBoot整合Quartz

2026/9/20 23:47:20 拓冰建站 浏览量
SpringBoot整合Quartz

添加依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

配置quartz属性

spring.quartz.properties.org.quartz.scheduler.instanceName=myScheduler
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
spring.quartz.properties.org.quartz.jobStore.tablePrefix=QRTZ_
spring.quartz.properties.org.quartz.jobStore.isClustered=true
spring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=20000

这是一个基本的Quartz配置,你可能需要根据你的需求进行修改。

创建Job

创建一个实现Job接口的类,该类定义了需要执行的任务逻辑。例如:

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;public class MyJob implements Job {@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {// 执行你的任务逻辑System.out.println("Job executed!");}
}

配置JobDetail和Trigger

在@Configuration类中配置JobDetail和Trigger,并将它们注册到Scheduler中:

import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class QuartzConfig {@Beanpublic JobDetail myJobDetail() {return JobBuilder.newJob(MyJob.class).withIdentity("myJob").storeDurably().build();}@Beanpublic Trigger myTrigger(JobDetail job) {return TriggerBuilder.newTrigger().forJob(job).withIdentity("myTrigger").withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();}
}

这里的myTrigger配置了一个简单的触发器,每隔10秒执行一次。

启用Quartz Scheduler

在你的应用主类上添加@EnableScheduling注解,以启用Spring的调度功能:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableScheduling
public class YourApplication {public static void main(String[] args) {SpringApplication.run(YourApplication.class, args);}
}

运行项目

现在,当你运行应用时,Quartz会自动调度你配置的任务。

以上只是一个简单的Quartz整合示例,你可能需要根据实际需求进行更复杂的配置。确保了解Quartz的相关概念,例如JobDetail、Trigger、Scheduler等。