Spring Boot提供了對Quartz任務調度框架的整合支持。Quartz是一個功能強大的任務調度框架,可以用于定時執行任務、計劃任務等。
要整合Quartz,首先需要添加Quartz的依賴。在pom.xml文件中添加以下依賴:
<!-- Quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
接下來,創建一個Quartz的配置類,用于配置Quartz的相關屬性和任務調度。
@Configuration
public class QuartzConfig {
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
// 設置觸發器
schedulerFactoryBean.setTriggers(trigger1().getObject(), trigger2().getObject());
// 設置任務
schedulerFactoryBean.setJobDetails(jobDetail1().getObject(), jobDetail2().getObject());
// 設置自動啟動
schedulerFactoryBean.setAutoStartup(true);
return schedulerFactoryBean;
}
@Bean
public JobDetailFactoryBean jobDetail1() {
JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
jobDetailFactoryBean.setJobClass(MyJob1.class);
jobDetailFactoryBean.setDurability(true);
jobDetailFactoryBean.setRequestsRecovery(true);
return jobDetailFactoryBean;
}
@Bean
public JobDetailFactoryBean jobDetail2() {
JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
jobDetailFactoryBean.setJobClass(MyJob2.class);
jobDetailFactoryBean.setDurability(true);
jobDetailFactoryBean.setRequestsRecovery(true);
return jobDetailFactoryBean;
}
@Bean
public CronTriggerFactoryBean trigger1() {
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(jobDetail1().getObject());
cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?");
return cronTriggerFactoryBean;
}
@Bean
public CronTriggerFactoryBean trigger2() {
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(jobDetail2().getObject());
cronTriggerFactoryBean.setCronExpression("0/10 * * * * ?");
return cronTriggerFactoryBean;
}
}
在上面的配置類中,我們創建了兩個JobDetail和兩個CronTrigger,并將它們添加到SchedulerFactoryBean中。這樣,當應用啟動時,Quartz會根據配置的觸發器和任務來執行定時任務。
最后,創建兩個Job類,用于處理具體的任務邏輯。
public class MyJob1 implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 任務邏輯
}
}
public class MyJob2 implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 任務邏輯
}
}
這樣,就完成了Spring Boot整合Quartz任務調度框架的配置。
如果需要將任務調度的配置進行持久化,可以使用Quartz提供的JobStore來實現。常用的JobStore有以下幾種:
要使用JDBCJobStore進行持久化配置,可以添加以下依賴:
<!-- Quartz JDBC -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jdbc</artifactId>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
接著,在Quartz的配置類中添加以下代碼:
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
// ...
// 設置持久化配置
schedulerFactoryBean.setDataSource(dataSource());
schedulerFactoryBean.setJobFactory(jobFactory());
return schedulerFactoryBean;
}
@Bean
public DataSource dataSource()