java中基于线层池Spring-quartz如何实现动态增删除改和暂停恢复定时任务
这篇文章主要讲解了“java中基于线层池Spring-quartz如何实现动态增删除改和暂停恢复定时任务”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“java中基于线层池Spring-quartz如何实现动态增删除改和暂停恢复定时任务”吧!
让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名注册、虚拟主机、营销软件、网站建设、云溪网站维护、网站推广。
注:本文中没有定时任务增删改查页面、保存数据库等操作的代码。根据实际需求自行完善
pom.xml
org.springframework spring-context-support 4.2.5.RELEASE org.quartz-scheduler quartz 2.2.1
spring-scheduler.xml
ApplicationContext.xml (spring配置文件)
ScheduleJobMode.java
package com.scheduler; import java.io.Serializable; import java.util.Date; /** * 定时任务mode */ public class ScheduleJobMode implements Serializable { private static final long serialVersionUID = 1L; //任务调度参数key public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY"; //任务id private String jobId; //spring bean名称 bean名称不能为空 private String beanName; //方法名 方法名称不能为空 private String methodName; //参数 private String params; //cron表达式 private String cronExpression; //任务状态 1:正常,2:暂停 private String status; //备注 private String remark; //创建者 private String createName; //创建时间 private Date createTime; //最近更新人 private String modifierName; //最近更新时间 private Date modifierTime; public void setJobId(String jobId) { this.jobId = jobId; } public String getJobId() { return jobId; } public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getParams() { return params; } public void setParams(String params) { this.params = params; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getCronExpression() { return cronExpression; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getCreateTime() { return createTime; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public String getModifierName() { return modifierName; } public void setModifierName(String modifierName) { this.modifierName = modifierName; } public Date getModifierTime() { return modifierTime; } public void setModifierTime(Date modifierTime) { this.modifierTime = modifierTime; } }
ScheduleJobLogMode.java
package com.scheduler; import java.io.Serializable; import java.util.Date; /** * 定时执行日志 */ public class ScheduleJobLogMode implements Serializable { private static final long serialVersionUID = 1L; //日志id private String logId; //任务id private String jobId; //spring bean名称 private String beanName; //方法名 private String methodName; //参数 private String params; //任务状态 0:成功 1:失败 private String status; //失败信息 private String error; //耗时(单位:毫秒) private Integer times; //创建时间 private Date createTime; public String getLogId() { return logId; } public void setLogId(String logId) { this.logId = logId; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getParams() { return params; } public void setParams(String params) { this.params = params; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getError() { return error; } public void setError(String error) { this.error = error; } public Integer getTimes() { return times; } public void setTimes(Integer times) { this.times = times; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
ScheduleUtils.java
package com.scheduler; import com.wawj.fg.common.scheduler.ScheduleJob; import com.wawj.fg.common.scheduler.support.TaskSupport; import com.scheduler.ScheduleJobMode; import org.quartz.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 定时任务工具类 */ public class ScheduleUtils { private static final Logger logger = LoggerFactory.getLogger(ScheduleUtils.class); private static final String JOB_NAME = "TASK_"; /** * 获取触发器key */ public static TriggerKey getTriggerKey(String jobId) { return TriggerKey.triggerKey(JOB_NAME + jobId); } /** * 获取jobKey */ public static JobKey getJobKey(String jobId) { return JobKey.jobKey(JOB_NAME + jobId); } /** * 获取表达式触发器 */ public static CronTrigger getCronTrigger(Scheduler scheduler, String jobId) { try { return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId)); } catch (SchedulerException e) { logger.info("获取定时任务CronTrigger出现异常", e); return null; } } /** * 创建定时任务 */ public static void createScheduleJob(Scheduler scheduler, ScheduleJobMode scheduleJob) { try { //构建job信息 JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId())).build(); //表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); //按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId())).withSchedule(scheduleBuilder).build(); //放入参数,运行时的方法可以获取 jobDetail.getJobDataMap().put(ScheduleJobMode.JOB_PARAM_KEY, scheduleJob); scheduler.scheduleJob(jobDetail, trigger); //暂停任务 if (scheduleJob.getStatus().equals(TaskSupport.TASK_STATUS_STOPPED)) { pauseJob(scheduler, scheduleJob.getJobId()); } } catch (SchedulerException e) { logger.info("创建定时任务失败", e); } } /** * 更新定时任务 */ public static void updateScheduleJob(Scheduler scheduler, ScheduleJobMode scheduleJob) { try { TriggerKey triggerKey = getTriggerKey(scheduleJob.getJobId()); //表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getJobId()); if (null != trigger) { //按新的cronExpression表达式重新构建trigger trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); //参数 trigger.getJobDataMap().put(ScheduleJobMode.JOB_PARAM_KEY, scheduleJob); scheduler.rescheduleJob(triggerKey, trigger); //暂停任务 if (scheduleJob.getStatus().equals(TaskSupport.TASK_STATUS_STOPPED)) { pauseJob(scheduler, scheduleJob.getJobId()); } } else { throw new NullPointerException(); } } catch (SchedulerException e) { logger.info("更新定时任务失败", e); } } /** * 立即执行任务 */ public static void run(Scheduler scheduler, ScheduleJobMode scheduleJob) { try { //参数 JobDataMap dataMap = new JobDataMap(); dataMap.put(ScheduleJobMode.JOB_PARAM_KEY, scheduleJob); scheduler.triggerJob(getJobKey(scheduleJob.getJobId()), dataMap); } catch (SchedulerException e) { logger.info("立即执行定时任务失败", e); } } /** * 暂停任务 */ public static void pauseJob(Scheduler scheduler, String jobId) { try { scheduler.pauseJob(getJobKey(jobId)); } catch (SchedulerException e) { logger.info("暂停定时任务失败", e); } } /** * 恢复任务 */ public static void resumeJob(Scheduler scheduler, String jobId) { try { scheduler.resumeJob(getJobKey(jobId)); } catch (SchedulerException e) { logger.info("暂停定时任务失败", e); } } /** * 删除定时任务 */ public static void deleteScheduleJob(Scheduler scheduler, String jobId) { try { scheduler.deleteJob(getJobKey(jobId)); } catch (SchedulerException e) { logger.info("删除定时任务失败", e); } } }
QuartzManager.java
package com.scheduler; import com.wawj.fg.common.scheduler.ScheduleUtils; import com.wawj.fg.model.baseinfo.scheduler.ScheduleJobMode; import org.quartz.CronTrigger; import org.quartz.Scheduler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.List; @Component public class QuartzManager { @Autowired private SchedulerFactoryBean schedulerFactoryBean; /** * 项目启动时,初始化定时器 */ @PostConstruct public void init() { //查询保存到数据的定时任务,本文没有操作数据代码,可自行完善 ListscheduleJobList = schedulerJobDao.queryList(new HashMap ()); Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (ScheduleJobMode scheduleJob : scheduleJobList) { CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId()); //如果不存在,则创建 if (cronTrigger == null) { ScheduleUtils.createScheduleJob(scheduler, scheduleJob); } else { ScheduleUtils.updateScheduleJob(scheduler, scheduleJob); } } } /** * 创建定时器 */ public void createScheduleJob(ScheduleJobMode scheduleJob) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); ScheduleUtils.createScheduleJob(scheduler, scheduleJob); } /** * 更新定时器 */ public void update(ScheduleJobMode scheduleJob) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); ScheduleUtils.updateScheduleJob(scheduler, scheduleJob); } /** * 删除定时器 */ public void deleteBatch(String[] jobIds) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (String jobId : jobIds) { ScheduleUtils.deleteScheduleJob(scheduler, jobId); } } /** * 立刻执行一下定时器 */ public void run(String[] jobIds) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (String jobId : jobIds) { //queryObject(jobId) 是从数据库中查询出对象 ScheduleUtils.run(scheduler, queryObject(jobId)); } } /** * 暂停定时任务 */ public void pause(String[] jobIds) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (String jobId : jobIds) { ScheduleUtils.pauseJob(scheduler, jobId); } } /** * 恢复定时任务 */ public void resume(String[] jobIds) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (String jobId : jobIds) { ScheduleUtils.resumeJob(scheduler, jobId); } } }
SpringUtils.java
package com.scheduler; import com.wawj.fg.util.SpringContextUtils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * Spring Context 工具类 */ @Component public class SpringUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtils.applicationContext = applicationContext; } public static Object getBean(String name) { return applicationContext.getBean(name); } public staticT getBean(String name, Class requiredType) { return applicationContext.getBean(name, requiredType); } public static boolean containsBean(String name) { return applicationContext.containsBean(name); } public static boolean isSingleton(String name) { return applicationContext.isSingleton(name); } public static Class extends Object> getType(String name) { return applicationContext.getType(name); } }
ScheduleRunnable.java
package com.scheduler; import java.lang.reflect.Method; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.util.ReflectionUtils; import com.scheduler;.SpringUtils; /** * 执行定时任务 */ public class ScheduleRunnable implements Runnable { private static final Logger logger = Logger.getLogger(ScheduleRunnable.class); //类名 private Object target; //方法名 private Method method; //参数 private String params; public ScheduleRunnable(String beanName, String methodName, String params) throws NoSuchMethodException{ this.target = SpringUtils.getBean(beanName); this.params = params; if(StringUtils.isNotBlank(params)){ this.method = target.getClass().getDeclaredMethod(methodName, String.class); }else{ this.method = target.getClass().getDeclaredMethod(methodName); } } @Override public void run() { try { ReflectionUtils.makeAccessible(method); if(StringUtils.isNotBlank(params)){ method.invoke(target, params); }else{ method.invoke(target); } }catch (Exception e) { logger.error("执行定时任务失败",e); throw new RuntimeException(); } } }
ScheduleJob.java
package com.scheduler; import com.wawj.fg.common.scheduler.ScheduleRunnable; import com.wawj.fg.model.baseinfo.scheduler.ScheduleJobLogMode; import com.wawj.fg.model.baseinfo.scheduler.ScheduleJobMode; import com.wawj.fg.service.baseinfo.scheduler.ScheduleJobLogService; import com.wawj.fg.util.SpringContextUtils; import com.wawj.fg.util.UUIDUtil; import org.apache.log4j.Logger; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * 定时任务 */ public class ScheduleJob extends QuartzJobBean { private static final Logger logger = Logger.getLogger(ScheduleJob.class); //创建线层池 (创建一个单线程化的线程池) private ExecutorService service = Executors.newSingleThreadExecutor(); @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { ScheduleJobMode scheduleJob = (ScheduleJobMode) context.getMergedJobDataMap() .get(ScheduleJobMode.JOB_PARAM_KEY); //获取spring bean ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService"); //数据库保存执行记录 ScheduleJobLogMode log = new ScheduleJobLogMode(); log.setLogId(UUIDUtil.getUUID()); log.setJobId(scheduleJob.getJobId()); log.setBeanName(scheduleJob.getBeanName()); log.setMethodName(scheduleJob.getMethodName()); log.setParams(scheduleJob.getParams()); log.setCreateTime(new Date()); //任务开始时间 long startTime = System.currentTimeMillis(); try { //执行任务 logger.info("任务准备执行,任务ID:" + scheduleJob.getJobId()); ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams()); Future> future = service.submit(task); future.get(); //任务执行总时长 long times = System.currentTimeMillis() - startTime; log.setTimes((int) times); //任务状态 0:成功 1:失败 log.setStatus("0"); logger.info("任务执行完毕,任务ID:" + scheduleJob.getJobId() + " 总共耗时:" + times + "毫秒"); } catch (Exception e) { logger.error("任务执行失败,任务ID:" + scheduleJob.getJobId(), e); //任务执行总时长 long times = System.currentTimeMillis() - startTime; log.setTimes((int) times); //任务状态 0:成功 1:失败 log.setStatus("1"); log.setError(scheduleJob.getBeanName() + "." + scheduleJob.getMethodName()); } finally { scheduleJobLogService.save(log); } } }
感谢各位的阅读,以上就是“java中基于线层池Spring-quartz如何实现动态增删除改和暂停恢复定时任务”的内容了,经过本文的学习后,相信大家对java中基于线层池Spring-quartz如何实现动态增删除改和暂停恢复定时任务这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!
标题名称:java中基于线层池Spring-quartz如何实现动态增删除改和暂停恢复定时任务
文章出自:http://myzitong.com/article/jiesec.html