博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring整合Quartz实现动态定时任务
阅读量:6583 次
发布时间:2019-06-24

本文共 14296 字,大约阅读时间需要 47 分钟。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hans201507/article/details/50593834

1.创建动态定时任务实体

import java.util.Date;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.SequenceGenerator;import javax.persistence.Table;/** * 动态定时任务 *  * @author *  */@Entity@Table(name = "SCHEDULE_JOB", schema = "JLW")public class ScheduleJob implements java.io.Serializable {	private static final long serialVersionUID = 7058240968903003001L;	private Integer id;	private Date createTime;	private Date updateTime;	private String jobName;// 任务名称	private String jobGroup;// 任务分组	private String jobStatus;// 任务状态 是否启动任务	private String cronExpression;// cron表达式	private String description;// 描述	private String beanClass;// 任务执行时调用哪个类的方法 包名+类名	private String isConcurrent;// 任务是否有状态(是否并发任务)	private String springId;// spring bean	private String methodName;// 任务调用的方法名	@SequenceGenerator(name = "generator", sequenceName = "SEQ_SCHEDULE_JOB")	@Id	@GeneratedValue(strategy = GenerationType.AUTO, generator = "generator")	@Column(name = "ID", unique = true, nullable = false, precision = 10, scale = 0)	public Integer getId() {		return id;	}	public void setId(Integer id) {		this.id = id;	}	@Column(name = "CREATETIME")	public Date getCreateTime() {		return createTime;	}	public void setCreateTime(Date createTime) {		this.createTime = createTime;	}	@Column(name = "UPDATETIME")	public Date getUpdateTime() {		return updateTime;	}	public void setUpdateTime(Date updateTime) {		this.updateTime = updateTime;	}	@Column(name = "JOBNAME")	public String getJobName() {		return jobName;	}	public void setJobName(String jobName) {		this.jobName = jobName;	}	@Column(name = "JOBGROUP")	public String getJobGroup() {		return jobGroup;	}	public void setJobGroup(String jobGroup) {		this.jobGroup = jobGroup;	}	@Column(name = "JOBSTATUS")	public String getJobStatus() {		return jobStatus;	}	public void setJobStatus(String jobStatus) {		this.jobStatus = jobStatus;	}	@Column(name = "CRONEXPRESSION")	public String getCronExpression() {		return cronExpression;	}	public void setCronExpression(String cronExpression) {		this.cronExpression = cronExpression;	}	@Column(name = "DESCRIPTION")	public String getDescription() {		return description;	}	public void setDescription(String description) {		this.description = description;	}	@Column(name = "BEANCLASS")	public String getBeanClass() {		return beanClass;	}	public void setBeanClass(String beanClass) {		this.beanClass = beanClass;	}	@Column(name = "ISCONCURRENT")	public String getIsConcurrent() {		return isConcurrent;	}	public void setIsConcurrent(String isConcurrent) {		this.isConcurrent = isConcurrent;	}	@Column(name = "SPRINGID")	public String getSpringId() {		return springId;	}	public void setSpringId(String springId) {		this.springId = springId;	}	@Column(name = "METHODNAME")	public String getMethodName() {		return methodName;	}	public void setMethodName(String methodName) {		this.methodName = methodName;	}}
2.实现实体的dao层与service层,这里仅给出service接口的代码

public interface ScheduleJobService {	List
findAll(); void save(ScheduleJob scheduleJob); void update(ScheduleJob scheduleJob); ScheduleJob findById(Integer id);}
3.实现系统动态定时任务管理service接口和实现

public interface ScheduleJobManageService {	/**	 * 添加任务	 * 	 * @param scheduleJob	 */	void addScheduleJob(ScheduleJob scheduleJob);	/**	 * 暂停任务	 * 	 * @param scheduleJob	 */	void pauseScheduleJob(ScheduleJob scheduleJob);	/**	 * 恢复任务	 * 	 * @param scheduleJob	 */	void resumeScheduleJob(ScheduleJob scheduleJob);	/**	 * 删除任务	 * 	 * @param scheduleJob	 */	void deleteScheduleJob(ScheduleJob scheduleJob);	/**	 * 立即执行任务	 * 	 * @param scheduleJob	 */	void runScheduleJobNow(ScheduleJob scheduleJob);	/**	 * 更新任务	 * 	 * @param scheduleJob	 */	void updateSchedule(ScheduleJob scheduleJob);	/**	 * 所有任务	 * 	 * @return	 */	List
getAllScheduleJob(); /** * 所有正在运行的任务 * * @return */ List
getAllScheduleJobRunning(); /** * 系统初始化添加计划任务 */ void init();}
@Service@Transactionalpublic class ScheduleJobManageServiceImpl implements ScheduleJobManageService {	public final Logger logger = Logger.getLogger(getClass());	@Autowired	private SchedulerFactoryBean schedulerFactoryBean;	@Resource	private ScheduleJobService scheduleJobService;	@Override	public void addScheduleJob(ScheduleJob scheduleJob) {		if (scheduleJob == null || !Constants.SCHEDULEJOB_STATUS_RUNNING.equals(scheduleJob.getJobStatus())) {			return;		}		Scheduler scheduler = schedulerFactoryBean.getScheduler();		logger.info("开始添加任务,任务:" + scheduleJob.getJobName());		try {			TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);			// 不存在,创建一个			if (trigger == null) {				Class clazz = Constants.SCHEDULEJOB_CONCURRENT_IS.equals(scheduleJob.getIsConcurrent()) ? ScheduleJobFactory.class : ScheduleJobFactoryNotCurrent.class;				JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).build();				jobDetail.getJobDataMap().put("scheduleJob", scheduleJob);				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());				trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(scheduleBuilder).build();				scheduler.scheduleJob(jobDetail, trigger);			} else {				// Trigger已存在,那么更新相应的定时设置				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());				// 按新的cronExpression表达式重新构建trigger				trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();				// 按新的trigger重新设置job执行				scheduler.rescheduleJob(triggerKey, trigger);			}		} catch (Exception e) {			logger.error("添加任务出错,任务:" + scheduleJob.getJobName());		}		logger.info("添加任务完成,任务:" + scheduleJob.getJobName());	}	@Override	public void pauseScheduleJob(ScheduleJob scheduleJob) {		try {			Scheduler scheduler = schedulerFactoryBean.getScheduler();			JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());			scheduler.pauseJob(jobKey);		} catch (Exception e) {			logger.error("暂停任务出错,任务:" + scheduleJob.getJobName());			throw new MyException("暂停任务出错,任务:" + scheduleJob.getJobName(), e);		}	}	@Override	public void resumeScheduleJob(ScheduleJob scheduleJob) {		try {			Scheduler scheduler = schedulerFactoryBean.getScheduler();			JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());			scheduler.resumeJob(jobKey);		} catch (Exception e) {			logger.error("恢复任务出错,任务:" + scheduleJob.getJobName());			throw new MyException("恢复任务出错,任务:" + scheduleJob.getJobName(), e);		}	}	@Override	public void deleteScheduleJob(ScheduleJob scheduleJob) {		try {			Scheduler scheduler = schedulerFactoryBean.getScheduler();			JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());			scheduler.deleteJob(jobKey);		} catch (Exception e) {			logger.error("删除任务出错,任务:" + scheduleJob.getJobName());			throw new MyException("删除任务出错,任务:" + scheduleJob.getJobName(), e);		}	}	@Override	public void runScheduleJobNow(ScheduleJob scheduleJob) {		try {			Scheduler scheduler = schedulerFactoryBean.getScheduler();			JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());			scheduler.triggerJob(jobKey);		} catch (Exception e) {			logger.error("立即启动任务出错,任务:" + scheduleJob.getJobName());			throw new MyException("立即启动任务出错,任务:" + scheduleJob.getJobName(), e);		}	}	@Override	public void updateSchedule(ScheduleJob scheduleJob) {		try {			Scheduler scheduler = schedulerFactoryBean.getScheduler();			TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();			scheduler.rescheduleJob(triggerKey, trigger);		} catch (Exception e) {			logger.error("更新任务出错,任务:" + scheduleJob.getJobName());			throw new MyException("更新任务出错,任务:" + scheduleJob.getJobName(), e);		}	}	@Override	public List
getAllScheduleJob() { try { Scheduler scheduler = schedulerFactoryBean.getScheduler(); GroupMatcher
matcher = GroupMatcher.anyJobGroup(); Set
jobKeys = scheduler.getJobKeys(matcher); List
jobList = new ArrayList
(); for (JobKey jobKey : jobKeys) { List
triggers = scheduler.getTriggersOfJob(jobKey); for (Trigger trigger : triggers) { ScheduleJob job = new ScheduleJob(); job.setJobName(jobKey.getName()); job.setJobGroup(jobKey.getGroup()); job.setDescription("触发器:" + trigger.getKey()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); job.setJobStatus(triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; String cronExpression = cronTrigger.getCronExpression(); job.setCronExpression(cronExpression); } jobList.add(job); } } return jobList; } catch (Exception e) { logger.error("获取系统所有任务出错!"); throw new MyException("获取系统所有任务出错!", e); } } @Override public List
getAllScheduleJobRunning() { try { Scheduler scheduler = schedulerFactoryBean.getScheduler(); List
executingJobs = scheduler.getCurrentlyExecutingJobs(); List
jobList = new ArrayList
(executingJobs.size()); for (JobExecutionContext executingJob : executingJobs) { ScheduleJob job = new ScheduleJob(); JobDetail jobDetail = executingJob.getJobDetail(); JobKey jobKey = jobDetail.getKey(); Trigger trigger = executingJob.getTrigger(); job.setJobName(jobKey.getName()); job.setJobGroup(jobKey.getGroup()); job.setDescription("触发器:" + trigger.getKey()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); job.setJobStatus(triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; String cronExpression = cronTrigger.getCronExpression(); job.setCronExpression(cronExpression); } jobList.add(job); } return jobList; } catch (Exception e) { logger.error("获取系统所有正在运行任务出错!"); throw new MyException("获取系统所有正在运行任务出错!", e); } } @Override public void init() { // 这里获取任务信息数据 List
jobList = scheduleJobService.findAll(); for (ScheduleJob scheduleJob : jobList) { addScheduleJob(scheduleJob); } }}
service实现需要调用的类

public class ScheduleJobFactory implements Job {	@Override	public void execute(JobExecutionContext context) throws JobExecutionException {		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");		ScheduleJobUtil.invokMethod(scheduleJob);	}}
import org.quartz.DisallowConcurrentExecution;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import com.tongdow.jianle.entity.ScheduleJob;@DisallowConcurrentExecutionpublic class ScheduleJobFactoryNotCurrent implements Job {	@Override	public void execute(JobExecutionContext context) throws JobExecutionException {		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");		ScheduleJobUtil.invokMethod(scheduleJob);	}}
public class ScheduleJobUtil {	public final static Logger logger = Logger.getLogger(ScheduleJobUtil.class);	/**	 * 通过反射调用scheduleJob中定义的方法	 * 	 * @param scheduleJob	 */	public static void invokMethod(ScheduleJob scheduleJob) {		Object object = null;		Class clazz = null;		try {			if (!Common.isNullOrEmpty(scheduleJob.getSpringId()) && SpringUtils.containsBean(scheduleJob.getSpringId())) {				object = SpringUtils.getBean(scheduleJob.getSpringId());			} else if (!Common.isNullOrEmpty(scheduleJob.getBeanClass())) {				clazz = Class.forName(scheduleJob.getBeanClass());				object = clazz.newInstance();			}			if (object == null) {				logger.error("任务:" + scheduleJob.getJobName() + ",结果:启动失败!");				return;			}			clazz = object.getClass();			Method method = null;			method = clazz.getDeclaredMethod(scheduleJob.getMethodName());			if (method != null) {				method.invoke(object);			} else {				logger.error("任务:" + scheduleJob.getJobName() + ",结果:启动失败!");				return;			}			logger.info("任务:" + scheduleJob.getJobName() + ",结果:启动成功!");		} catch (Exception e) {			logger.error("任务:" + scheduleJob.getJobName() + ",结果:启动失败!,原因:" + e.getMessage());			throw new MyException("计划任务启动出错", e);		}	}}
4.动态定时任务的执行方法

@Componentpublic class JobTask {	public Logger logger = Logger.getLogger(getClass());	@Resource	private GoodsOrdersService goodsOrdersService;	public void goodsOrder() {		logger.info("商品订单处理定时任务开始!");		logger.info("商品订单处理定时任务结束!");	}	public void order() {		logger.info("订单处理定时任务开始!");		logger.info("订单处理定时任务结束!");	}}
5.Spring配置文件需加入的内容

 
配置文件说明,如果只需要动态定时任务,则只需要

其他的为非动态定时任务
如果配置了这个
则实体类可以springId字段可以指定jobTask,前提是执行任务的方法是写在这个bean里的。

6.用到的常量

/** * 常量定义 *  * @author *  */public class Constants {	// 计划任务 状态和是否有状态	public static final String SCHEDULEJOB_STATUS_RUNNING = "1";// 启动任务	public static final String SCHEDULEJOB_STATUS_NOT_RUNNING = "0";// 不启动任务	public static final String SCHEDULEJOB_CONCURRENT_IS = "1";// 有状态	public static final String SCHEDULEJOB_CONCURRENT_NOT = "0";// 无状态}
7.系统初始化

	logger.info("系统开始初始化");	// 获取容器与相关的Service对象	ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());	ScheduleJobManageService scheduleJobManageService = ac.getBean(ScheduleJobManageService.class);	// 初始化系统动态定时任务	scheduleJobManageService.init();	logger.info("系统初始化完成");
结束,有问题可以qq135018413

你可能感兴趣的文章
图片转流
查看>>
ubunto应用软件
查看>>
HTML 标签说明
查看>>
锋利的jQuery-2--判断jQuery获取到的对象是否存在$().length
查看>>
linux 查询系统版本命令、查询端口号是否被占用命令
查看>>
java笔记八:IO流之字符流与字符缓冲流
查看>>
Docker 命令收集
查看>>
myeclipse注册码生成器
查看>>
怎样快速学好PHP技术之PHP学习方法总结
查看>>
iOS App间相互跳转漫谈 part2
查看>>
Java CAS 原理剖析
查看>>
ISCC2014 writeup
查看>>
Kotlin 知识梳理(1) Kotlin 基础
查看>>
js正则表达式
查看>>
iOS socket通信,编解码,浮点型数据解析
查看>>
手把手教你如何新建scrapy爬虫框架的第一个项目(下)
查看>>
前端基础15:JS作用域基础
查看>>
Linux系统相关命令
查看>>
BATJ面试必会之 Spring 篇(一)
查看>>
表驱动法
查看>>