说明:Quartz是一个定时器框架,可以实现定时任务,本文介绍如何在Spring Boot项目中整合Quartz框架,Quartz介绍参看下面这篇文章:
创建Demo
首先,创建一个Spring Boot项目,pom文件如下:
<?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>2.7.12</version>
<relativePath/>
</parent>
<groupId>com.hezy</groupId>
<artifactId>quartz_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
引入quartz
在pom文件中,添加下面依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
引入依赖后就可以使用了,Spring Boot向来很方便。首先,创建一个定时任务,如下:
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(System.currentTimeMillis() / 1000 + "===============定时任务开始执行了……");
}
}
然后,创建定时任务的配置类,配置类配置定时任务的周期等信息,如下:
import com.hezy.job.SampleJob;
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 static org.quartz.SimpleScheduleBuilder.simpleSchedule;
@Configuration
public class QuartzConfig {
/**
* 定义JobDetail,关联具体的Job
*/
@Bean
public JobDetail sampleJobDetail() {
return JobBuilder.newJob(SampleJob.class)
.withIdentity("sampleJob").storeDurably().build();
}
/**
* 关联Trigger
* 定时任务,每隔10秒执行一次
*/
@Bean
public Trigger sampleJobTrigger() {
return TriggerBuilder.newTrigger().forJob(sampleJobDetail())
.withIdentity("sampleTrigger")
.withSchedule(simpleSchedule().repeatForever()
.withIntervalInSeconds(10))
.build();
}
}
执行,查看效果,如下:
可以看到,项目刚启动就立即执行了一次,往后每隔十秒执行一次。我想是否项目一启动就执行,应该有相关的配置可以设置的。
总结
本文介绍了如何在Spring Boot整合Quartz框架
标签:Quartz,Spring,boot,Boot,quartz,org,import,定时 From: https://blog.csdn.net/qq_42108331/article/details/141336278