在Spring Boot中整合Quartz,可以实现定时任务调度的功能
1、首先,在pom.xml
文件中添加Quartz和Spring Boot Starter Quartz的依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId>
</dependency>
2、创建一个定时任务类,实现Job
接口,并重写execute()
方法,在该方法中编写具体的定时任务逻辑。这里以打印当前时间为例:
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.time.LocalDateTime;public class MyJob implements Job {@Overridepublic void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {// 在这里编写定时任务的逻辑System.out.println("Current time: " + LocalDateTime.now());}
}
3、创建一个Quartz配置类,配置JobDetail和Trigger。这里以每隔5秒执行一次任务为例:
import org.quartz.JobBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;@Configuration
public class QuartzConfig {// 配置JobDetail@Beanpublic JobDetailFactoryBean jobDetail() {JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();factoryBean.setJobClass(MyJob.class); // 设置Job类return factoryBean;}// 配置Trigger@Beanpublic SimpleTriggerFactoryBean trigger(JobDetailFactoryBean jobDetail) {SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();factoryBean.setJobDetail(jobDetail.getObject()); // 设置JobDetailfactoryBean.setRepeatInterval(5000); // 设置执行间隔,单位毫秒factoryBean.setRepeatCount(SimpleTriggerFactoryBean.REPEAT_INDEFINITELY); // 设置重复次数,这里设置为无限次return factoryBean;}
}
4、在Spring Boot的启动类上添加@EnableScheduling
注解,启用定时任务功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableScheduling
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
现在,当应用启动后,定时任务就会按照配置执行。在这个例子中,会每隔5秒执行一次MyJob
中定义的任务。
本文只是教大家简单使用,如果需要Quartz定时任务做管理任务,可以直接复用若依框架的Quartz模块,他们这个做的挺好的
地址:RuoYi: 🎉 基于SpringBoot的权限管理系统 易读易懂、界面简洁美观。 核心技术采用Spring、MyBatis、Shiro没有任何其它重度依赖。直接运行即可用