這篇文章主要講解了“java中基于線層池Spring-quartz如何實(shí)現(xiàn)動(dòng)態(tài)增刪除改和暫?;謴?fù)定時(shí)任務(wù)”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“java中基于線層池Spring-quartz如何實(shí)現(xiàn)動(dòng)態(tài)增刪除改和暫停恢復(fù)定時(shí)任務(wù)”吧!
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名注冊(cè)、虛擬主機(jī)、營(yíng)銷軟件、網(wǎng)站建設(shè)、云溪網(wǎng)站維護(hù)、網(wǎng)站推廣。
注:本文中沒(méi)有定時(shí)任務(wù)增刪改查頁(yè)面、保存數(shù)據(jù)庫(kù)等操作的代碼。根據(jù)實(shí)際需求自行完善
pom.xml
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency>
spring-scheduler.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"/> </beans>
ApplicationContext.xml (spring配置文件)
<!-- 增加quartz定時(shí)任務(wù)管理配置 --> <import resource="spring-scheduler.xml"/>
ScheduleJobMode.java
package com.scheduler; import java.io.Serializable; import java.util.Date; /** * 定時(shí)任務(wù)mode */ public class ScheduleJobMode implements Serializable { private static final long serialVersionUID = 1L; //任務(wù)調(diào)度參數(shù)key public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY"; //任務(wù)id private String jobId; //spring bean名稱 bean名稱不能為空 private String beanName; //方法名 方法名稱不能為空 private String methodName; //參數(shù) private String params; //cron表達(dá)式 private String cronExpression; //任務(wù)狀態(tài) 1:正常,2:暫停 private String status; //備注 private String remark; //創(chuàng)建者 private String createName; //創(chuàng)建時(shí)間 private Date createTime; //最近更新人 private String modifierName; //最近更新時(shí)間 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; /** * 定時(shí)執(zhí)行日志 */ public class ScheduleJobLogMode implements Serializable { private static final long serialVersionUID = 1L; //日志id private String logId; //任務(wù)id private String jobId; //spring bean名稱 private String beanName; //方法名 private String methodName; //參數(shù) private String params; //任務(wù)狀態(tài) 0:成功 1:失敗 private String status; //失敗信息 private String error; //耗時(shí)(單位:毫秒) private Integer times; //創(chuàng)建時(shí)間 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; /** * 定時(shí)任務(wù)工具類 */ public class ScheduleUtils { private static final Logger logger = LoggerFactory.getLogger(ScheduleUtils.class); private static final String JOB_NAME = "TASK_"; /** * 獲取觸發(fā)器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); } /** * 獲取表達(dá)式觸發(fā)器 */ public static CronTrigger getCronTrigger(Scheduler scheduler, String jobId) { try { return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId)); } catch (SchedulerException e) { logger.info("獲取定時(shí)任務(wù)CronTrigger出現(xiàn)異常", e); return null; } } /** * 創(chuàng)建定時(shí)任務(wù) */ public static void createScheduleJob(Scheduler scheduler, ScheduleJobMode scheduleJob) { try { //構(gòu)建job信息 JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId())).build(); //表達(dá)式調(diào)度構(gòu)建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); //按新的cronExpression表達(dá)式構(gòu)建一個(gè)新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId())).withSchedule(scheduleBuilder).build(); //放入?yún)?shù),運(yùn)行時(shí)的方法可以獲取 jobDetail.getJobDataMap().put(ScheduleJobMode.JOB_PARAM_KEY, scheduleJob); scheduler.scheduleJob(jobDetail, trigger); //暫停任務(wù) if (scheduleJob.getStatus().equals(TaskSupport.TASK_STATUS_STOPPED)) { pauseJob(scheduler, scheduleJob.getJobId()); } } catch (SchedulerException e) { logger.info("創(chuàng)建定時(shí)任務(wù)失敗", e); } } /** * 更新定時(shí)任務(wù) */ public static void updateScheduleJob(Scheduler scheduler, ScheduleJobMode scheduleJob) { try { TriggerKey triggerKey = getTriggerKey(scheduleJob.getJobId()); //表達(dá)式調(diào)度構(gòu)建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getJobId()); if (null != trigger) { //按新的cronExpression表達(dá)式重新構(gòu)建trigger trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); //參數(shù) trigger.getJobDataMap().put(ScheduleJobMode.JOB_PARAM_KEY, scheduleJob); scheduler.rescheduleJob(triggerKey, trigger); //暫停任務(wù) if (scheduleJob.getStatus().equals(TaskSupport.TASK_STATUS_STOPPED)) { pauseJob(scheduler, scheduleJob.getJobId()); } } else { throw new NullPointerException(); } } catch (SchedulerException e) { logger.info("更新定時(shí)任務(wù)失敗", e); } } /** * 立即執(zhí)行任務(wù) */ public static void run(Scheduler scheduler, ScheduleJobMode scheduleJob) { try { //參數(shù) JobDataMap dataMap = new JobDataMap(); dataMap.put(ScheduleJobMode.JOB_PARAM_KEY, scheduleJob); scheduler.triggerJob(getJobKey(scheduleJob.getJobId()), dataMap); } catch (SchedulerException e) { logger.info("立即執(zhí)行定時(shí)任務(wù)失敗", e); } } /** * 暫停任務(wù) */ public static void pauseJob(Scheduler scheduler, String jobId) { try { scheduler.pauseJob(getJobKey(jobId)); } catch (SchedulerException e) { logger.info("暫停定時(shí)任務(wù)失敗", e); } } /** * 恢復(fù)任務(wù) */ public static void resumeJob(Scheduler scheduler, String jobId) { try { scheduler.resumeJob(getJobKey(jobId)); } catch (SchedulerException e) { logger.info("暫停定時(shí)任務(wù)失敗", e); } } /** * 刪除定時(shí)任務(wù) */ public static void deleteScheduleJob(Scheduler scheduler, String jobId) { try { scheduler.deleteJob(getJobKey(jobId)); } catch (SchedulerException e) { logger.info("刪除定時(shí)任務(wù)失敗", 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; /** * 項(xiàng)目啟動(dòng)時(shí),初始化定時(shí)器 */ @PostConstruct public void init() { //查詢保存到數(shù)據(jù)的定時(shí)任務(wù),本文沒(méi)有操作數(shù)據(jù)代碼,可自行完善 List<ScheduleJobMode> scheduleJobList = schedulerJobDao.queryList(new HashMap<String, Object>()); Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (ScheduleJobMode scheduleJob : scheduleJobList) { CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId()); //如果不存在,則創(chuàng)建 if (cronTrigger == null) { ScheduleUtils.createScheduleJob(scheduler, scheduleJob); } else { ScheduleUtils.updateScheduleJob(scheduler, scheduleJob); } } } /** * 創(chuàng)建定時(shí)器 */ public void createScheduleJob(ScheduleJobMode scheduleJob) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); ScheduleUtils.createScheduleJob(scheduler, scheduleJob); } /** * 更新定時(shí)器 */ public void update(ScheduleJobMode scheduleJob) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); ScheduleUtils.updateScheduleJob(scheduler, scheduleJob); } /** * 刪除定時(shí)器 */ public void deleteBatch(String[] jobIds) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (String jobId : jobIds) { ScheduleUtils.deleteScheduleJob(scheduler, jobId); } } /** * 立刻執(zhí)行一下定時(shí)器 */ public void run(String[] jobIds) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (String jobId : jobIds) { //queryObject(jobId) 是從數(shù)據(jù)庫(kù)中查詢出對(duì)象 ScheduleUtils.run(scheduler, queryObject(jobId)); } } /** * 暫停定時(shí)任務(wù) */ public void pause(String[] jobIds) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); for (String jobId : jobIds) { ScheduleUtils.pauseJob(scheduler, jobId); } } /** * 恢復(fù)定時(shí)任務(wù) */ 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 static <T> T getBean(String name, Class<T> 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; /** * 執(zhí)行定時(shí)任務(wù) */ public class ScheduleRunnable implements Runnable { private static final Logger logger = Logger.getLogger(ScheduleRunnable.class); //類名 private Object target; //方法名 private Method method; //參數(shù) 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("執(zhí)行定時(shí)任務(wù)失敗",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; /** * 定時(shí)任務(wù) */ public class ScheduleJob extends QuartzJobBean { private static final Logger logger = Logger.getLogger(ScheduleJob.class); //創(chuàng)建線層池 (創(chuàng)建一個(gè)單線程化的線程池) 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"); //數(shù)據(jù)庫(kù)保存執(zhí)行記錄 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()); //任務(wù)開(kāi)始時(shí)間 long startTime = System.currentTimeMillis(); try { //執(zhí)行任務(wù) logger.info("任務(wù)準(zhǔn)備執(zhí)行,任務(wù)ID:" + scheduleJob.getJobId()); ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams()); Future<?> future = service.submit(task); future.get(); //任務(wù)執(zhí)行總時(shí)長(zhǎng) long times = System.currentTimeMillis() - startTime; log.setTimes((int) times); //任務(wù)狀態(tài) 0:成功 1:失敗 log.setStatus("0"); logger.info("任務(wù)執(zhí)行完畢,任務(wù)ID:" + scheduleJob.getJobId() + " 總共耗時(shí):" + times + "毫秒"); } catch (Exception e) { logger.error("任務(wù)執(zhí)行失敗,任務(wù)ID:" + scheduleJob.getJobId(), e); //任務(wù)執(zhí)行總時(shí)長(zhǎng) long times = System.currentTimeMillis() - startTime; log.setTimes((int) times); //任務(wù)狀態(tài) 0:成功 1:失敗 log.setStatus("1"); log.setError(scheduleJob.getBeanName() + "." + scheduleJob.getMethodName()); } finally { scheduleJobLogService.save(log); } } }
感謝各位的閱讀,以上就是“java中基于線層池Spring-quartz如何實(shí)現(xiàn)動(dòng)態(tài)增刪除改和暫?;謴?fù)定時(shí)任務(wù)”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)java中基于線層池Spring-quartz如何實(shí)現(xiàn)動(dòng)態(tài)增刪除改和暫停恢復(fù)定時(shí)任務(wù)這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
網(wǎng)站名稱:java中基于線層池Spring-quartz如何實(shí)現(xiàn)動(dòng)態(tài)增刪除改和暫?;謴?fù)定時(shí)任務(wù)
文章起源:http://www.rwnh.cn/article42/jiesec.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、企業(yè)網(wǎng)站制作、全網(wǎng)營(yíng)銷推廣、網(wǎng)站導(dǎo)航、搜索引擎優(yōu)化、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)