SpringBoot整合Quartz实现定时任务
简介
Quartz是一个很牛的任务调度框架,通过它我们可以实现诸如:定时活动、延时活动、订单状态延时检测、服务器状态定时检测等,时间调度任务功能。
下面我们介绍一下它在SpringBoot中的使用:
- 1.配置Quartz
- 2.静态任务调度
- 3.动态任务调度
- 4.任务调度监听器
快速集成
快速集成体验一下Quartz的功能吧。
- 1.首先引入maven依赖
<!--Quartz-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
- 2.配置Quartz
SpringBoot集成Quartz依然沿用了Spring的典型方式,使用工厂Bean生成Bean的方式。在Quartz中,需要被调度的任务叫做Job,而负责调度任务则是Scheduler。
我们首先需要配置工厂Bean:JobFactory接口,自定义一个AutowiringSpringBeanJobFactory类继承SpringBeanJobFactory(实现了JobFactory接口)
AutowiringSpringBeanJobFactory工厂类将负责生成实现了Job接口的类的实例对象Bean。
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
/**
自动注入的jobBean工厂
*/
public class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory
implements ApplicationContextAware {private transient AutowireCapableBeanFactory beanFactory;
public void setApplicationContext(final ApplicationContext context) {beanFactory = context.getAutowireCapableBeanFactory();
}
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = super.createJobInstance(bundle);beanFactory.autowireBean(job); <span class="hljs-keyword">return</span> job;
}
}
下面创建一个Quartz的config配置类:SchedulerConfig
SchedulerConfig类通过 @Configuration 自动装载配置。这里它配置了两种Bean工厂,一个是JobFactory ,另一个是SchedulerFactoryBean。JobFactory就是上面我们所说的AutowiringSpringBeanJobFactory,而SchedulerFactoryBean是Quartz为我们提供的一个生成Scheduler实例Bean的工厂类。
而在这个SchedulerConfig类中还提供了simpleJobTrigger()【表达式任务触发器工厂】和quartzProperties()【Properties属性基本配置参数】
- CronTriggerFactoryBean为我们提供了执行任务的触发器,这里是通过静态方式配置了一个调度任务。
- quartzProperties配置参数可以自由配置Quartz的一些基本参数属性,比如配置调度线程数,调度线程池类型等,这里只配置了一个基本使用参数,如果需要更多请查阅官网。
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import java.util.Properties;
/**
-
定时配置(可以配置静态定时任务)
*/
@Configuration
public class SchedulerConfig {
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
<span class="hljs-keyword">return</span> jobFactory;
}
//SchedulerFactoryBean
@Bean
public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, Trigger simpleJobTrigger)
throws IOException{
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setJobFactory(jobFactory);
factory.setQuartzProperties(quartzProperties());
factory.setTriggers(simpleJobTrigger);
<span class="hljs-keyword">return</span> factory;
}
/**
-
静态方式配置定时任务
-
@param jobDetail
-
@return
*/
@Bean
public CronTriggerFactoryBean simpleJobTrigger(@Qualifier("simpleJobDetail") JobDetail jobDetail) {
CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean ();
factoryBean.setJobDetail(jobDetail);
factoryBean.setStartDelay(1000L);
factoryBean.setName("trigger1");
factoryBean.setGroup("group1");
//周1至周5,每天上午8点至下午18点,每分钟执行一次
factoryBean.setCronExpression("0 0/1 8-18 ? * 2-6");
return factoryBean;
}
@Bean
public JobDetailFactoryBean simpleJobDetail() {
JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
factoryBean.setJobClass(ScheduledJob.class);
factoryBean.setGroup(<span class="hljs-string">"group1"</span>);
factoryBean.setName(<span class="hljs-string">"job1"</span>);
<span class="hljs-keyword">return</span> factoryBean;
}
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(<span class="hljs-keyword">new</span> ClassPathResource(<span class="hljs-string">"/quartz.properties"</span>));
propertiesFactoryBean.afterPropertiesSet();
<span class="hljs-keyword">return</span> propertiesFactoryBean.getObject();
}
}
quartz.properties内容:
#------配置调度器的线程池
#线程池类
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#线程个数
org.quartz.threadPool.threadCount = 3
#------配置任务调度现场数据保存机制,默认保存在内存
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
- 3.自定义一个任务Job
创建 ScheduledJob.java 并实现Job接口,它是我们之后任务被调度后执行业务逻辑的主要类,通过execute()方法执行:
import org.jboss.logging.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
自定义定时任务
*/
public class ScheduledJob implements Job {private static final Logger logger= Logger.getLogger(ScheduledJob.class);
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {<span class="hljs-comment">//执行任务逻辑....</span> logger.info(<span class="hljs-string">"执行自定义定时任务"</span>);
}
}
-
4.自定义开启关闭任务的管理器类
为了之后项目中使用方便我们抽象出一个任务调度管理类 SchedulerManager.java,我们开启、暂停、恢复、停止、移除所有任务额功能都是通过它去执行。
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
/*
-
此处可以注入数据库操作,查询出所有的任务配置
*/
@Component
public class SchedulerManager {
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
private JobListener scheduleListener;
/**
- 开始定时任务
- @param jobName
- @param jobGroup
- @throws SchedulerException
*/
public void startJob(String cron,String jobName,String jobGroup,Class<? extends Job> jobClass) throws SchedulerException
{
Scheduler scheduler = schedulerFactoryBean.getScheduler();
if(scheduleListener==null){
scheduleListener=new SchedulerListener();
scheduler.getListenerManager().addJobListener(scheduleListener);
}
JobKey jobKey=new JobKey(jobName,jobGroup);
if(!scheduler.checkExists(jobKey))
{
scheduleJob(cron,scheduler,jobName,jobGroup,jobClass);
}
}
/**
- 移除定时任务
- @param jobName
- @param jobGroup
- @throws SchedulerException
/
public void deleteJob(String jobName,String jobGroup) throws SchedulerException
{
Scheduler scheduler = schedulerFactoryBean.getScheduler();
JobKey jobKey=new JobKey(jobName,jobGroup);
scheduler.deleteJob(jobKey);
}
/*
- 暂停定时任务
- @param jobName
- @param jobGroup
- @throws SchedulerException
/
public void pauseJob(String jobName,String jobGroup) throws SchedulerException
{
Scheduler scheduler = schedulerFactoryBean.getScheduler();
JobKey jobKey=new JobKey(jobName,jobGroup);
scheduler.pauseJob(jobKey);
}
/*
- 恢复定时任务
- @param jobName
- @param jobGroup
- @throws SchedulerException
/
public void resumeJob(String jobName,String jobGroup) throws SchedulerException
{
Scheduler scheduler = schedulerFactoryBean.getScheduler();
JobKey triggerKey=new JobKey(jobName,jobGroup);
scheduler.resumeJob(triggerKey);
}
/*
- 清空所有当前scheduler对象下的定时任务【目前只有全局一个scheduler对象】
- @throws SchedulerException
*/
public void clearAll() throws SchedulerException {
Scheduler scheduler = schedulerFactoryBean.getScheduler();
scheduler.clear();
}
/**
-
动态创建Job
-
此处的任务可以配置可以放到properties或者是放到数据库中
-
Trigger:name和group 目前和job的name、group一致,之后可以扩展归类
-
@param scheduler
-
@throws SchedulerException
/
private void scheduleJob(String cron,Scheduler scheduler,String jobName,String jobGroup,Class<? extends Job> jobClass) throws SchedulerException{
/
- 此处可以先通过任务名查询数据库,如果数据库中存在该任务,更新任务的配置以及触发器
- 如果此时数据库中没有查询到该任务,则按照下面的步骤新建一个任务,并配置初始化的参数,并将配置存到数据库中
*/
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroup).build();
// 每5s执行一次
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail,cronTrigger);
}
}
任务监听器SchedulerListener.java:
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
public class SchedulerListener implements JobListener {
public static final String LISTENER_NAME = "QuartSchedulerListener";
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> LISTENER_NAME; <span class="hljs-comment">//must return a name</span>
}
<span class="hljs-comment">//任务被调度前</span>
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">jobToBeExecuted</span><span class="hljs-params">(JobExecutionContext context)</span> </span>{
String jobName = context.getJobDetail().getKey().toString();
System.out.println(<span class="hljs-string">"jobToBeExecuted"</span>);
System.out.println(<span class="hljs-string">"Job : "</span> + jobName + <span class="hljs-string">" is going to start..."</span>);
}
<span class="hljs-comment">//任务调度被拒了</span>
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">jobExecutionVetoed</span><span class="hljs-params">(JobExecutionContext context)</span> </span>{
System.out.println(<span class="hljs-string">"jobExecutionVetoed"</span>);
<span class="hljs-comment">//可以做一些日志记录原因</span>
}
<span class="hljs-comment">//任务被调度后</span>
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">jobWasExecuted</span><span class="hljs-params">(JobExecutionContext context,
JobExecutionException jobException)</span> </span>{
System.out.println(<span class="hljs-string">"jobWasExecuted"</span>);
String jobName = context.getJobDetail().getKey().toString();
System.out.println(<span class="hljs-string">"Job : "</span> + jobName + <span class="hljs-string">" is finished..."</span>);
<span class="hljs-keyword">if</span> (jobException!=<span class="hljs-keyword">null</span>&&!jobException.getMessage().equals(<span class="hljs-string">""</span>)) {
System.out.println(<span class="hljs-string">"Exception thrown by: "</span> + jobName
+ <span class="hljs-string">" Exception: "</span> + jobException.getMessage());
}
}
}
这里涉及到Quartz的一些概念,有必要在这里简单说明一下:
Job: 被执行的任务
Scheduler: 负责调度任务,如:开始/结束一个调度
Trigger: 负责执行任务的触发器(这里我用的是CronTrigger可以用cron表达式去执行任务的触发器)如:"0/5 * * * * ?" //每五秒执行一次,具体使用方法可以查阅一下官网。
JobDetail: 封装Job,Scheduler真正调度的对象,包括Job名称,组等信息。
JobListener: 任务执行的监听器,可以监听到任务执行前、后以及未能成功执行抛出异常。
5.使用示例:
这里我写了一个简单的Controller去开启/停止任务调度:
import com.yu.scloud.baseframe.frame.utils.quartz.ScheduledJob;
import com.yu.scloud.baseframe.frame.utils.quartz.SchedulerManager;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/quartz")
public class QuartzController{
<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">public</span> SchedulerManager myScheduler;
<span class="hljs-meta">@RequestMapping</span>(value = <span class="hljs-string">"/job2"</span>,method = RequestMethod.GET)
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">scheduleJob2</span><span class="hljs-params">()</span>
</span>{
<span class="hljs-keyword">try</span> {
myScheduler.startJob(<span class="hljs-string">"0/5 * * * * ?"</span>,<span class="hljs-string">"job2"</span>,<span class="hljs-string">"group2"</span>, ScheduledJob.class);<span class="hljs-comment">//每五秒执行一次</span>
<span class="hljs-comment">//0 0/5 14 * * ?在每天下午2点到下午2:55期间的每5分钟触发</span>
<span class="hljs-comment">//0 50 14 * * ?在每天下午2点50分5秒执行一次</span>
// myScheduler.startJob("5 50 14 * * ?","job2","group2", ScheduledJob.class);
return "启动定时器成功";
} catch (SchedulerException e) {
e.printStackTrace();
}
return "启动定时器失败";
}
@RequestMapping(value = "/del_job2",method = RequestMethod.GET)
public String deleteScheduleJob2()
{
try {
myScheduler.deleteJob("job2","group2");
return "删除定时器成功";
} catch (SchedulerException e) {
e.printStackTrace();
}
return "删除定时器失败";
}
}
启动服务,访问就会开启一个定时任务,可以打开控制台查看打印信息。OK!关于在SpringBoot中Quartz定时任务调度的使用,就介绍到这里。
</div>
</div>