0. POM依赖
org.quartz.scheduler.instanceName=DefaultQuartzScheduler
org.quartz.threadPool.threadCount=3
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
org.quartz.plugin.jobInitializer.class=org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
org.quartz.plugin.jobInitializer.fileNames=quartz-config.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound=true
2. 创建QuartzConfig.java配置类,读取和解释XML
import org.quartz.Scheduler;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
// https://cloud.tencent.com/developer/article/1947192
/**
* Quartz 配置类
* <p>
* 该类提供Quartz配置,同时也自动加载数据库中和文件的任务配置:<ul>
* <li>定时间隔和时间点</li>
* <li>要检查和的页面地址和API清单</li>
* </ul>
*/
@Configuration
public class QuartzConfig {
// @Bean
// public JobDetail jobDetail() {
// // 指定任务描述具体的实现类
// return JobBuilder.newJob(CheckServicePerformanceJob.class)
// // 指定任务的名称
// .withIdentity("ABC_CHECK_SP")
// // 任务描述
// .withDescription("任务描述:定时检查服务性能")
// // 每次任务执行后进行存储
// .storeDurably()
// .build();
// }
//
// @Bean
// public Trigger trigger() {
// // 创建触发器
// return TriggerBuilder.newTrigger()
// // 绑定工作任务
// .forJob(jobDetail())
// // 每隔一段时间执行一次 job
// .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(600))
// .build();
// }
@Autowired
private JobFactory jobFactory;
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
/**
* 当触发器触发时,与之关联的任务被Scheduler中配置的JobFactory实例化,也就是每触发一次,就会创建一个任务的实例化对象
* (如果缺省)则调用Job类的newInstance方法生成一个实例
* (这里选择自定义)并将创建的Job实例化交给IoC管理
*
* @return
*/
@Bean
public JobFactory jobFactory() {
return new AdaptableJobFactory() {
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
};
}
/**
* 配置SchedulerFactoryBean
* <p>
* 将一个方法产生为Bean并交给Spring容器管理
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
// Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setJobFactory(jobFactory);
//这句一定要加!!!!不然properties配置不生效!!!!
factory.setConfigLocation(new ClassPathResource("/quartz.properties"));
factory.setStartupDelay(1);
factory.afterPropertiesSet();
// 设置自定义Job Factory,用于Spring管理Job bean
return factory;
}
@Bean(name = "scheduler")
public Scheduler scheduler() throws Exception {
Scheduler scheduler = schedulerFactoryBean().getScheduler();
// 启动Schedule的时候,调整任务触发器
scheduler.getListenerManager().addSchedulerListener(new SchedulerListenerSupport() {
@Override
public void jobAdded(JobDetail jobDetail) {
JobKey key = jobDetail.getKey();
QuartzManager.modifyJobTime(key.getName(), key.getGroup(), "新的cron表达式"));
}
}
});
return scheduler;
}
}
3. quartz-config.xml文件内容:
// 下面是每隔一分钟,自动运行xxx.xxx.xxx.CheckServicePerformanceJob任务一次。
<?xml version="1.0" encoding="UTF-8"?>
<job-scheduling-data
xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData
http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd"
version="1.8">
<schedule>
<job>
<name>ABC_CHECK_SP</name>
<group>ABC_GROUP</group>
<description>Health Check Job</description>
<job-class>xxx.xxx.xxx.CheckServicePerformanceJob</job-class>
</job>
<trigger>
<cron>
<name>ABC_CHECK_SP</name>
<group>ABC_CHECK_SP</group>
<job-name>ABC_CHECK_SP</job-name>
<job-group>ABC_GROUP</job-group>
<!-- It will run every 5 minutes -->
<!-- 秒 分 时 日 月 星期-->
<cron-expression>0 */1 * * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>
4. 任务实现类:
xxx.xxx.xxx.CheckServicePerformanceJob.java:
public class CheckServicePerformanceJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
Log.debug("CheckServicePerformanceJob.executeInternal() 定时任务开始");
// 这里写上你的定时任务代码实现代码
Log.debug("CheckServicePerformanceJob.executeInternal() 定时任务结束");
}
}
5. Quartz工具类:
// springboot+quartz定时任务(解决无法注入bean及持久化的问题)_oneSeventeenCode的博客-CSDN博客
package xxx.xxx.xxx.performance.utils;
import XLog;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Quartz 工具类
* <p>
* 提供 Quartz 任务的删除,添加,修改,启动,停止等基本操作
*
* @author kingron
* @version 1.0
*/
@Service
public class QuartzManager {
public static Scheduler scheduler;
// 创建 schedulerFactory 工厂
private static SchedulerFactory scheduleFactory = new StdSchedulerFactory();
public QuartzManager(Scheduler scheduler) {
this.scheduler = scheduler;
}
/**
* 添加一个定时任务
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @param jobClass 任务类名
* @param cron Crontab时间表达式(秒 分 时 日 月 星期),例如: "0/10 * * * * ?"
* @param params 附加参数,如 beginDate, endDate
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static boolean addJob(String jobName, String jobGroupName,
String triggerName, String triggerGroupName,
Class<? extends Job> jobClass,
String cron, Map<String, Object> params) throws Exception {
Date beginDate = (Date) params.get("beginDate");
Date endDate = (Date) params.get("endDate");
if (!isValidExpression(cron)) {
throw new SchedulerConfigException("Wrong cron expression");
}
try {
// 任务名,任务组,任务执行类
JobDetail job = JobBuilder.newJob(jobClass)
.withIdentity(jobName, jobGroupName).build();
// 任务参数
job.getJobDataMap().putAll(params);
// if (null == beginDate) {
// beginDate = new Date();
// beginDate.setTime(beginDate.getTime() + 5000);
// } else {
// beginDate.setTime(beginDate.getTime() - 5000);
// }
// endDate.setTime(endDate.getTime() + 200000);
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
// 创建Trigger对象
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withIdentity(triggerName, triggerGroupName)
.usingJobData(triggerName, triggerGroupName)
.startNow() //立即生效
.startAt(beginDate)
.endAt(endDate)
.withSchedule(CronScheduleBuilder.cronSchedule(cron))
.withSchedule(CronScheduleBuilder.cronSchedule(cron)
.withMisfireHandlingInstructionDoNothing())
.build();
// 调度容器设置JobDetail和Trigger
scheduler.scheduleJob(job, cronTrigger);
// 启动
if (!scheduler.isShutdown()) {
scheduler.start();
}
Log.debug("QuartzManager.addJob() 成功: 任务名称=" + jobName + ", 任务组=" + jobGroupName);
return true;
} catch (Exception e) {
Log.error("QuartzManager.addJob() 失败: 任务名称=" + jobName + ", 任务组=" + jobGroupName + ", 错误信息: " + e.getMessage());
return false;
}
}
/**
* 修改一个任务的触发时间
*
* @param jobName 触发器名
* @param jobGroupName 触发器组名
* @param cron 时间设置,参考quartz说明文档,必须是cron类型的触发器才会修改
*/
public static boolean modifyJobTime(String jobName, String jobGroupName, String cron) {
try {
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(JobKey.jobKey(jobName, jobGroupName));
if (triggers == null) {
return false;
}
for (Trigger trigger: triggers) {
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String oldTime = cronTrigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(cron)) {
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(jobName, jobGroupName);
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
// 创建Trigger对象
CronTrigger newTrigger = (CronTrigger) triggerBuilder.build();
// 方式一 :修改一个任务的触发时间
scheduler.rescheduleJob(cronTrigger.getKey(), newTrigger);
}
}
}
return true;
} catch (Exception e) {
Log.error("QuartzManager.modifyJobTime() 出错: " + e.getMessage());
return false;
}
}
/**
* 移除一个任务
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @return 删除结果,成功返回 true, 失败返回 false
*/
public static boolean removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
// 停止触发器
scheduler.pauseTrigger(triggerKey);
// 移除触发器
scheduler.unscheduleJob(triggerKey);
// 删除任务
return scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
} catch (Exception e) {
Log.debug("QuartzManager.removeJob() 删除任务失败: " + e.getMessage());
return false;
}
}
/**
* 获取任务是否存在
* <p><center>[wp_ad_camp_3]</center></p><p>
* STATE_BLOCKED 4 阻塞
* STATE_COMPLETE 2 完成
* STATE_ERROR 3 错误
* STATE_NONE -1 不存在
* STATE_NORMAL 0 正常
* STATE_PAUSED 1 暂停
*/
public Boolean notExists(String triggerName, String triggerGroupName) {
try {
return scheduler.getTriggerState(TriggerKey.triggerKey(triggerName, triggerGroupName)) == Trigger.TriggerState.NONE;
} catch (Exception e) {
Log.error("QuartzManager.notExists() 错误: " + e.getMessage());
return false;
}
}
/**
* 启动所有定时任务
*/
public static void startJobs() {
try {
Scheduler scheduler = scheduleFactory.getScheduler();
scheduler.start();
} catch (SchedulerException e) {
Log.error("QuartzManager.startJobs() 失败: " + e.getMessage());
}
}
/**
* 关闭所有定时任务
*/
public static void stopJobs() {
try {
Scheduler scheduler = scheduleFactory.getScheduler();
if (!scheduler.isShutdown()) {
scheduler.shutdown();
}
} catch (SchedulerException e) {
Log.error("QuartzManager.stopJobs() 失败: " + e.getMessage());
}
}
/**
* 从数据库中找到已经存在的job,并重新开户调度
*/
public static void resumeJob() {
try {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
//获取调度器中所有的触发器组
List<String> triggerGroups = scheduler.getTriggerGroupNames();
//遍历获取每个触发器组
for (int i = 0; i < triggerGroups.size(); i++) {
List<String> triggers = scheduler.getTriggerGroupNames();
//遍历每个触发器组
for (int j = 0; j < triggers.size(); j++) {
//获取每个触发器
Trigger tg = scheduler.getTrigger(new TriggerKey(triggers
.get(j), triggerGroups.get(i)));
// 重新恢复在tgroup1组中,名为trigger1_1触发器的运行
// if (tg instanceof SimpleTrigger
// && tg.getDescription().equals("group1.trigger1")) {
//恢复运行
scheduler.resumeJob(new JobKey(triggers.get(j),
triggerGroups.get(i)));
// }
}
}
scheduler.start();
} catch (Exception e) {
Log.error("QuartzManager.resumeJob() 出错: " + e.getMessage());
}
}
/**
* 判断cron时间表达式正确性
*
* @param cronExpression 待验证的 cron 表达式,例如: "0/10 * * * * ?"
* @return 正确返回 true, 不正确返回 false
*/
public static boolean isValidExpression(final String cronExpression) {
CronTriggerImpl trigger = new CronTriggerImpl();
try {
trigger.setCronExpression(cronExpression);
Date date = trigger.computeFirstFireTime(null);
return date != null && date.after(new Date());
} catch (ParseException e) {
Log.error("QuartzManager.isValidExpression() 出错: " + e.getMessage());
}
return false;
}
}
例如修改或者删除Quartz任务:
boolean data = false;
// 删除任务
data = QuartzManager.removeJob("ABC_CHECK_SP", "ABC_GROUP", "ABC_CHECK_SP", "ABC_GROUP");
// 修改指定任务的cron触发器,例如从上面xml中的1分钟一次,改为5分钟一次
data = QuartzManager.modifyJobTime("ABC_CHECK_SP", "ABC_GROUP", "0 */5 * * * ?");