Springboot 整合 Quartz(定时任务框架)
在Spring Boot中整合Quartz来创建定时任务,你需要以下步骤:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 创建一个定时任务的Job类:
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class SampleJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 你的任务逻辑
System.out.println("定时任务执行中...");
}
}
- 配置Quartz定时任务:
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
public class QuartzConfig {
@Bean
public JobDetail sampleJobDetail() {
return JobBuilder.newJob(SampleJob.class)
.withIdentity("sampleJob")
.storeDurably()
.build();
}
@Bean
public Trigger sampleJobTrigger() {
return TriggerBuilder.newTrigger()
.forJob(sampleJobDetail())
.withIdentity("sampleTrigger")
.withSchedule(
// 每隔10秒执行一次
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever())
.build();
}
}
- 在
application.properties
或application.yml
中配置Quartz属性(如果需要):
# 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
以上步骤完成了Spring Boot整合Quartz的基本配置,运行Spring Boot应用后,定时任务将按照配置执行。
评论已关闭