开源框架Quartz动态添加、修改和删除定时任务 (二)

时间:2021-11-15 07:52:21

貌似每次回过头去看之前写的一些东西,总感觉不是很完美~~虽说不做完美人,但也要做完美事!这次主要是针对Quartz的动态维护和Spring集成,简单粗暴一点,直接上代码,有什么不了解留言交流

先来一个定时任务相关准备工作

package com.hupu.timertask;

/**
 * 任务调度类
 * @author Joyce.Luo
 * @date 2015-3-31 下午03:32:04
 * @version V3.0
 * @since Tomcat6.0,Jdk1.6
 * @copyright Copyright (c) 2015
 */
public class QuartzJob {
	/**
	 * 任务ID
	 */
	private Integer jobId;

	/**
	 * 任务名称
	 */
	private String jobName;

	/**
	 * 任务分组
	 */
	private String jobGroup;

	/**
	 * 任务状态 0禁用 1启用 2删除
	 */
	private Integer jobStatus;

	/**
	 * 任务运行时间表达式
	 */
	private String cronExpression;

	/**
	 * @return the jobId
	 */
	public Integer getJobId() {
		return jobId;
	}

	/**
	 * @param jobId
	 *            the jobId to set
	 */
	public void setJobId(Integer jobId) {
		this.jobId = jobId;
	}

	/**
	 * @return the jobName
	 */
	public String getJobName() {
		return jobName;
	}

	/**
	 * @param jobName
	 *            the jobName to set
	 */
	public void setJobName(String jobName) {
		this.jobName = jobName;
	}

	/**
	 * @return the jobGroup
	 */
	public String getJobGroup() {
		return jobGroup;
	}

	/**
	 * @param jobGroup
	 *            the jobGroup to set
	 */
	public void setJobGroup(String jobGroup) {
		this.jobGroup = jobGroup;
	}

	/**
	 * @return the jobStatus
	 */
	public Integer getJobStatus() {
		return jobStatus;
	}

	/**
	 * @param jobStatus
	 *            the jobStatus to set
	 */
	public void setJobStatus(Integer jobStatus) {
		this.jobStatus = jobStatus;
	}

	/**
	 * @return the cronExpression
	 */
	public String getCronExpression() {
		return cronExpression;
	}

	/**
	 * @param cronExpression
	 *            the cronExpression to set
	 */
	public void setCronExpression(String cronExpression) {
		this.cronExpression = cronExpression;
	}
}

定时任务

package com.hupu.timertask;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdScheduler;

/**
 * 任务调度管理类
 * @author Joyce.Luo
 * @date 2015-3-31 下午03:42:30
 * @version V3.0
 * @since Tomcat6.0,Jdk1.6
 * @copyright Copyright (c) 2015
 */
public class QuartzManager {
	private static final Logger logger = LogManager.getLogger(QuartzManager.class.getName());
	private StdScheduler scheduler;
	
	/**
	 * @param scheduler the scheduler to set
	 */
	public void setScheduler(StdScheduler scheduler) {
		this.scheduler = scheduler;
	}
	
	/**
	 * 初始化任务调度
	 * @author Joyce.Luo
	 * @date 2015-3-31 下午03:48:55
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	@SuppressWarnings("unchecked")
	public void initJob(QuartzJob job, Class cls){
		logger.info("初始化任务调度");
		try {
			TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
			if (null == trigger) {
				addQuartzJob(job, trigger, cls);
			}
		} catch (Exception e) {
			logger.error("初始化任务调度异常!" + e.getMessage(), e);
		}
	}
	
	/**
	 * 向任务调度中添加定时任务
	 * @param job 定时任务信息
	 * @param trigger 定时调度触发器
	 * @author Joyce.Luo
	 * @date 2015-3-31 下午04:04:58
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	@SuppressWarnings("unchecked")
	private void addQuartzJob(QuartzJob job, CronTrigger trigger, Class cls){
		logger.info("向任务调度中添加定时任务");
		try {
			JobDetail jobDetail = JobBuilder.newJob(cls)
				.withIdentity(job.getJobName(), job.getJobGroup()).build();
			jobDetail.getJobDataMap().put(job.getJobName(), job);
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
				.withSchedule(scheduleBuilder).build();
			scheduler.scheduleJob(jobDetail, trigger);
		} catch (Exception e) {
			logger.error("向任务调度中添加定时任务异常!" + e.getMessage(), e);
		}
	}
	
	/**
	 * 立即运行定时任务
	 * @param job 定时任务信息
	 * @author Joyce.Luo
	 * @date 2015-4-20 下午02:08:41
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	void runJob(QuartzJob job){
		logger.info("立即运行任务调度中的定时任务");
		try {
			if (null == job) {
				logger.info("定时任务信息为空,无法立即运行");
				return;
			}
			JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
			if(null == jobKey){
				logger.info("任务调度中不存在[" + job.getJobName() + "]定时任务,不予立即运行!");
				return;
			}
			scheduler.triggerJob(jobKey);
		} catch (Exception e) {
			logger.error("立即运行任务调度中的定时任务异常!" + e.getMessage(), e);
		}
	}
	
	/**
	 * 修改任务调度中的定时任务
	 * @param job 定时任务信息
	 * @param triggerKey 定时调度触发键
	 * @param trigger 定时调度触发器
	 * @author Joyce.Luo
	 * @date 2015-3-31 下午04:16:54
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	void updateQuartzJob(QuartzJob job, TriggerKey triggerKey, CronTrigger trigger){
		logger.info("修改任务调度中的定时任务");
		try {
			if (null == job || null == triggerKey || null == trigger) {
				logger.info("修改调度任务参数不正常!");
				return;
			}
			logger.info("原始任务表达式:" + trigger.getCronExpression()
					+ ",现在任务表达式:" + job.getCronExpression());
			if (trigger.getCronExpression().equals(job.getCronExpression())) {
				logger.info("任务调度表达式一致,不予进行修改!");
				return;
			}
			logger.info("任务调度表达式不一致,进行修改");
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
			scheduler.rescheduleJob(triggerKey, trigger);
		} catch (Exception e) {
			logger.error("修改任务调度中的定时任务异常!" + e.getMessage(), e);
		}
	}
	
	/**
	 * 暂停任务调度中的定时任务
	 * @param job 定时任务信息
	 * @author Joyce.Luo
	 * @date 2015-4-20 下午02:22:53
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	void pauseJob(QuartzJob job){
		logger.info("暂停任务调度中的定时任务");
		try {
			if (null == job) {
				logger.info("暂停调度任务参数不正常!");
				return;
			}
			JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
			if(null == jobKey){
				logger.info("任务调度中不存在[" + job.getJobName() + "]定时任务,不予进行暂停!");
				return;
			}
			scheduler.pauseJob(jobKey);
		} catch (Exception e) {
			logger.error("暂停任务调度中的定时任务异常!" + e.getMessage(), e);
		}
	}
	
	/**
	 * 恢复任务调度中的定时任务
	 * @param job 定时任务信息
	 * @author Joyce.Luo
	 * @date 2015-4-20 下午02:26:08
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	void resumeJob(QuartzJob job){
		logger.info("恢复任务调度中的定时任务");
		try {
			if (null == job) {
				logger.info("恢复调度任务参数不正常!");
				return;
			}
			JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
			if(null == jobKey){
				logger.info("任务调度中不存在[" + job.getJobName() + "]定时任务,不予进行恢复!");
				return;
			}
			scheduler.resumeJob(jobKey);
		} catch (Exception e) {
			logger.error("恢复任务调度中的定时任务异常!" + e.getMessage(), e);
		}
	}
	
	/**
	 * 删除任务调度中的定时任务
	 * @param job 定时任务信息
	 * @author Joyce.Luo
	 * @date 2015-3-31 下午04:30:03
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	void deleteJob(QuartzJob job){
		logger.info("删除任务调度中的定时任务");
		try {
			if (null == job) {
				logger.info("删除调度任务参数不正常!");
				return;
			}
			JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
			if(null == jobKey){
				logger.info("任务调度中不存在[" + job.getJobName() + "]定时任务,不予进行删除!");
				return;
			}
			scheduler.deleteJob(jobKey);
		} catch (Exception e) {
			logger.error("删除任务调度中的定时任务异常!" + e.getMessage(), e);
		}
	}
	
	/**
	 * 删除任务调度定时器
	 * @param triggerKey
	 * @author Joyce.Luo
	 * @date 2015-3-31 下午04:35:33
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2015
	 */
	void deleteJob(TriggerKey triggerKey){
		logger.info("删除任务调度定时器");
		try {
			if(null == triggerKey){
				logger.info("停止任务定时器参数不正常,不予进行停止!");
				return;
			}
			logger.info("停止任务定时器");
			scheduler.pauseTrigger(triggerKey);
			scheduler.unscheduleJob(triggerKey);
		} catch (Exception e) {
			logger.info("删除任务调度定时器异常!" + e.getMessage() ,e);
		}
	}
}

任务调度工厂

package com.hupu.timertask;

import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.hupu.util.FormatUtil;

/**
 * 任务调度工厂类
 * @author Joyce.Luo
 * @date 2015-3-31 下午03:38:35
 * @version V3.0
 * @since Tomcat6.0,Jdk1.6
 * @copyright Copyright (c) 2015
 */
public class QuartzJobFactory implements Job {
	private static final Logger logger = LogManager.getLogger(QuartzJobFactory.class.getName());
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		QuartzJob scheduleJob = (QuartzJob)context.getMergedJobDataMap().get("backup_job");
		logger.info("定时任务开始执行,任务名称[" + scheduleJob.getJobName() + "]");
		Date previousFireTime = context.getPreviousFireTime();
		if(null != previousFireTime){
			logger.info("定时任务上次调度时间:" + FormatUtil.formatDate(previousFireTime));
		}
		logger.info("定时任务下次调度时间:" + FormatUtil.formatDate(context.getNextFireTime()));
		// 执行业务逻辑
	}
}

到这里代码基本结束,至于Spring的配置,这个就不用多讲了哈~~~

得嘞,简单的讲到这里吧