SpringBoot或者SpringMvc+quartz2.2.1实现定时任务的增删改,启动自动添加任务
1、pom文件:
<!--quartz-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
2、SpringBoot启动类注入SchedulerFactoryBean或者SpringMvc配置文件新增xml配置
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
// Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
SchedulerFactoryBean factory = new SchedulerFactoryBean();
return factory;
}
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" />
3、新建管理类,并初始化加载任务
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* 定时任务管理
* @author: dy.yin 2021/3/10 9:25
*/
@Component
public class QuartzManager {
private static Logger LOGGER = LoggerFactory.getLogger(QuartzManager.class);
private static String JOB_GROUP_NAME = "YDY_JOBGROUP_NAME";
private static String TRIGGER_GROUP_NAME = "YDY_TRIGGERGROUP_NAME";
private Scheduler scheduler;
public QuartzManager(Scheduler scheduler){
this.scheduler = scheduler;
}
/**
* 添加定时任务
* @Title: addJob
* @author: dy.yin 2021/3/10 9:35
* @param: [jobName, jobClass, cron]
* @return: void
* @throws
*/
public void addJob(String jobName, String triggerName, Class jobClass, String cron) {
LOGGER.info("新增任务开始。。。。");
try {
// 任务名,任务组,任务执行类
JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(triggerName, TRIGGER_GROUP_NAME);
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
// 创建Trigger对象
CronTrigger trigger = (CronTrigger) triggerBuilder.build();
// 调度容器设置JobDetail和Trigger
scheduler.scheduleJob(jobDetail, trigger);
// 启动
if (!scheduler.isShutdown()) {
scheduler.start();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
LOGGER.info("新增任务结束。。。。");
}
/**
* 修改定时任务的时间
* @Title: modifyJobTime
* @author: dy.yin 2021/3/10 14:51
* @param: [scheduler, jobName, cron]
* @return: void
* @throws
*/
public void modifyJobTime(String jobName, String triggerName, String cron) {
LOGGER.info("修改任务开始。。。。");
try {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, TRIGGER_GROUP_NAME);
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
if (trigger == null) {
return;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(cron)) {
/** 方式一 :调用 rescheduleJob 开始 */
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(triggerKey);
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
// 创建Trigger对象
trigger = (CronTrigger) triggerBuilder.build();
// 方式一 :修改一个任务的触发时间
scheduler.rescheduleJob(triggerKey, trigger);
/** 方式一 :调用 rescheduleJob 结束 */
/** 方式二:先删除,然后在创建一个新的Job */
//JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
//Class<? extends Job> jobClass = jobDetail.getJobClass();
//removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
//addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);
/** 方式二 :先删除,然后在创建一个新的Job */
}
} catch (Exception e) {
throw new RuntimeException(e);
}
LOGGER.info("修改任务结束。。。。");
}
/**
* 删除一个任务
* @Title: removeJob
* @author: dy.yin 2021/3/10 14:59
* @param: [scheduler, jobName]
* @return: void
* @throws
*/
public void removeJob(String jobName) {
LOGGER.info("删除{}任务开始。。。。",jobName);
try {
scheduler.deleteJob(JobKey.jobKey(jobName, JOB_GROUP_NAME));// 删除任务
} catch (Exception e) {
throw new RuntimeException(e);
}
LOGGER.info("删除{}任务结束。。。。",jobName);
}
/**
* 初始化加载所有的自动化处理任务
* @Title: init
* @author: dy.yin 2021/3/10 15:25
* @return: void
* @throws
*/
@PostConstruct
public void init() {
/**
* 1、查询数据库配置任务
* 2、循环添加任务到触发器
* 3、界面提供修改任务执行的cron表达式(停止任务可以修改其他参数)
* 4、启动和停止任务调用添加任务和移除任务方法
*/
//每分钟执行一次 可以自己修改
addJob("任务处理", "任务处理", MarketHandleJob.class,"0 */1 * * * ?");
}
}
5、新建任务类,实现Job接口
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MarketHandleJob implements Job {
private static Logger LOGGER = LoggerFactory.getLogger(MarketHandleJob.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
LOGGER.info("处理任务开始{},参数为{}", System.currentTimeMillis(),context);
}
}
解决job类无法注入bean的问题
新增工具类
package com.ydy.common.util;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public class SpringUtils implements BeanFactoryPostProcessor {
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getAliases(name);
}
/**
* 获取aop代理对象
*
* @param invoker
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker)
{
return (T) AopContext.currentProxy();
}
}