spring boot集成quartz
Spring Boot 整合 Quartz 主要涉及到以下几个步骤:
- 添加依赖
- 配置 Quartz
- 创建 Job
- 创建 Trigger
- 配置 JobDetail
- 启动调度器
以下是一个简单的示例:
- 添加 Maven 依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
</dependencies>
- 配置 Quartz,在 application.properties 或 application.yml 中添加配置:
# application.properties
spring.quartz.job-store-type=memory
spring.quartz.properties.org.quartz.scheduler.instanceName=my-quartz-scheduler
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
- 创建 Job:
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Hello, Quartz!");
}
}
- 创建 Trigger:
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Date;
@Configuration
public class QuartzConfiguration {
@Bean
public Trigger helloTrigger() {
return TriggerBuilder.newTrigger()
.forJob(helloJobDetail())
.withIdentity("helloTrigger")
.startAt(new Date()) // 立即启动
.build();
}
}
- 配置 JobDetail:
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfiguration {
@Bean
public JobDetail helloJobDetail() {
return JobBuilder.newJob(HelloJob.class)
.withIdentity("helloJob")
.build();
}
}
- 启动调度器:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
}
}
以上代码提供了一个简单的 Spring Boot 整合 Qua
评论已关闭