Spring内置任务调度如何实现添加、取消与重置详解
前言
大家应该都有所体会,使用spring的任务调度给我们的开发带来了极大的便利,不过当我们的任务调度配置完成后,很难再对其进行更改,除非停止服务器,修改配置,然后再重启,显然这样是不利于线上操作的,为了实现动态的任务调度修改,我在网上也查阅了一些资料,大部分都是基于quartz实现的,使用spring内置的任务调度则少之又少,而且效果不理想,需要在下次任务执行后,新的配置才能生效,做不到立即生效。本着探索研究的原则,查看了一下spring的源码,下面为大家提供一种spring内置任务调度实现添加、取消、重置的方法。话不多说了,来一起看看详细的介绍 吧。
实现方法如下
首先,我们需要启用spring的任务调度
<?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" xmlns:task="http://www.springframework.org/schema/task" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <task:annotation-driven executor="jobexecutor" scheduler="jobscheduler" /> <task:executor id="jobexecutor" pool-size="5"/> <task:scheduler id="jobscheduler" pool-size="10" /> </beans>
这一部分配置在网上是很常见的,接下来我们需要联合使用@enablescheduling与org.springframework.scheduling.annotation.schedulingconfigurer
便携我们自己的调度配置,在schedulingconfigurer接口中,需要实现一个void configuretasks(scheduledtaskregistrar taskregistrar);
方法,传统做法是在该方法中添加需要执行的调度信息。网上的基本撒谎那个也都是使用该方法实现的,使用addtriggertask添加任务,并结合cron表达式动态修改调度时间,这里我们并不这样做。
查看一下scheduledtaskregistrar源码,我们发现该对象初始化完成后会执行scheduletasks()
方法,在该方法中添加任务调度信息,最终所有的任务信息都存放在名为scheduledfutures的集合中。
protected void scheduletasks() { long now = system.currenttimemillis(); if (this.taskscheduler == null) { this.localexecutor = executors.newsinglethreadscheduledexecutor(); this.taskscheduler = new concurrenttaskscheduler(this.localexecutor); } if (this.triggertasks != null) { for (triggertask task : this.triggertasks) { this.scheduledfutures.add(this.taskscheduler.schedule( task.getrunnable(), task.gettrigger())); } } if (this.crontasks != null) { for (crontask task : this.crontasks) { this.scheduledfutures.add(this.taskscheduler.schedule( task.getrunnable(), task.gettrigger())); } } if (this.fixedratetasks != null) { for (intervaltask task : this.fixedratetasks) { if (task.getinitialdelay() > 0) { date starttime = new date(now + task.getinitialdelay()); this.scheduledfutures.add(this.taskscheduler.scheduleatfixedrate( task.getrunnable(), starttime, task.getinterval())); } else { this.scheduledfutures.add(this.taskscheduler.scheduleatfixedrate( task.getrunnable(), task.getinterval())); } } } if (this.fixeddelaytasks != null) { for (intervaltask task : this.fixeddelaytasks) { if (task.getinitialdelay() > 0) { date starttime = new date(now + task.getinitialdelay()); this.scheduledfutures.add(this.taskscheduler.schedulewithfixeddelay( task.getrunnable(), starttime, task.getinterval())); } else { this.scheduledfutures.add(this.taskscheduler.schedulewithfixeddelay( task.getrunnable(), task.getinterval())); } } } }
所以我的思路就是动态修改该集合,实现任务调度的添加、取消、重置。实现代码如下:
package com.jianggujin.web.util.job; import java.util.map; import java.util.set; import java.util.concurrent.concurrenthashmap; import java.util.concurrent.scheduledfuture; import org.springframework.scheduling.taskscheduler; import org.springframework.scheduling.annotation.enablescheduling; import org.springframework.scheduling.annotation.schedulingconfigurer; import org.springframework.scheduling.config.scheduledtaskregistrar; import org.springframework.scheduling.config.triggertask; import com.jianggujin.web.util.beanutils; /** * 默认任务调度配置 * * @author jianggujin * */ @enablescheduling public class defaultschedulingconfigurer implements schedulingconfigurer { private final string field_scheduled_futures = "scheduledfutures"; private scheduledtaskregistrar taskregistrar; private set<scheduledfuture<?>> scheduledfutures = null; private map<string, scheduledfuture<?>> taskfutures = new concurrenthashmap<string, scheduledfuture<?>>(); @override public void configuretasks(scheduledtaskregistrar taskregistrar) { this.taskregistrar = taskregistrar; } @suppresswarnings("unchecked") private set<scheduledfuture<?>> getscheduledfutures() { if (scheduledfutures == null) { try { scheduledfutures = (set<scheduledfuture<?>>) beanutils.getproperty(taskregistrar, field_scheduled_futures); } catch (nosuchfieldexception e) { throw new schedulingexception("not found scheduledfutures field."); } } return scheduledfutures; } /** * 添加任务 * * @param taskid * @param triggertask */ public void addtriggertask(string taskid, triggertask triggertask) { if (taskfutures.containskey(taskid)) { throw new schedulingexception("the taskid[" + taskid + "] was added."); } taskscheduler scheduler = taskregistrar.getscheduler(); scheduledfuture<?> future = scheduler.schedule(triggertask.getrunnable(), triggertask.gettrigger()); getscheduledfutures().add(future); taskfutures.put(taskid, future); } /** * 取消任务 * * @param taskid */ public void canceltriggertask(string taskid) { scheduledfuture<?> future = taskfutures.get(taskid); if (future != null) { future.cancel(true); } taskfutures.remove(taskid); getscheduledfutures().remove(future); } /** * 重置任务 * * @param taskid * @param triggertask */ public void resettriggertask(string taskid, triggertask triggertask) { canceltriggertask(taskid); addtriggertask(taskid, triggertask); } /** * 任务编号 * * @return */ public set<string> taskids() { return taskfutures.keyset(); } /** * 是否存在任务 * * @param taskid * @return */ public boolean hastask(string taskid) { return this.taskfutures.containskey(taskid); } /** * 任务调度是否已经初始化完成 * * @return */ public boolean inited() { return this.taskregistrar != null && this.taskregistrar.getscheduler() != null; } }
其中用到的beanutils源码如下:
package com.jianggujin.web.util; import java.lang.reflect.field; import java.lang.reflect.method; import java.lang.reflect.modifier; import java.util.arraylist; import java.util.collections; import java.util.hashmap; import java.util.list; import java.util.map; public class beanutils { public static field findfield(class<?> clazz, string name) { try { return clazz.getfield(name); } catch (nosuchfieldexception ex) { return finddeclaredfield(clazz, name); } } public static field finddeclaredfield(class<?> clazz, string name) { try { return clazz.getdeclaredfield(name); } catch (nosuchfieldexception ex) { if (clazz.getsuperclass() != null) { return finddeclaredfield(clazz.getsuperclass(), name); } return null; } } public static method findmethod(class<?> clazz, string methodname, class<?>... paramtypes) { try { return clazz.getmethod(methodname, paramtypes); } catch (nosuchmethodexception ex) { return finddeclaredmethod(clazz, methodname, paramtypes); } } public static method finddeclaredmethod(class<?> clazz, string methodname, class<?>... paramtypes) { try { return clazz.getdeclaredmethod(methodname, paramtypes); } catch (nosuchmethodexception ex) { if (clazz.getsuperclass() != null) { return finddeclaredmethod(clazz.getsuperclass(), methodname, paramtypes); } return null; } } public static object getproperty(object obj, string name) throws nosuchfieldexception { object value = null; field field = findfield(obj.getclass(), name); if (field == null) { throw new nosuchfieldexception("no such field [" + name + "]"); } boolean accessible = field.isaccessible(); field.setaccessible(true); try { value = field.get(obj); } catch (exception e) { throw new runtimeexception(e); } field.setaccessible(accessible); return value; } public static void setproperty(object obj, string name, object value) throws nosuchfieldexception { field field = findfield(obj.getclass(), name); if (field == null) { throw new nosuchfieldexception("no such field [" + name + "]"); } boolean accessible = field.isaccessible(); field.setaccessible(true); try { field.set(obj, value); } catch (exception e) { throw new runtimeexception(e); } field.setaccessible(accessible); } public static map<string, object> obj2map(object obj, map<string, object> map) { if (map == null) { map = new hashmap<string, object>(); } if (obj != null) { try { class<?> clazz = obj.getclass(); do { field[] fields = clazz.getdeclaredfields(); for (field field : fields) { int mod = field.getmodifiers(); if (modifier.isstatic(mod)) { continue; } boolean accessible = field.isaccessible(); field.setaccessible(true); map.put(field.getname(), field.get(obj)); field.setaccessible(accessible); } clazz = clazz.getsuperclass(); } while (clazz != null); } catch (exception e) { throw new runtimeexception(e); } } return map; } /** * 获得父类集合,包含当前class * * @param clazz * @return */ public static list<class<?>> getsuperclasslist(class<?> clazz) { list<class<?>> clazzes = new arraylist<class<?>>(3); clazzes.add(clazz); clazz = clazz.getsuperclass(); while (clazz != null) { clazzes.add(clazz); clazz = clazz.getsuperclass(); } return collections.unmodifiablelist(clazzes); } }
因为加载的延迟,在使用这种方法自定义配置任务调度是,首先需要调用inited()
方法判断是否初始化完成,否则可能出现错误。
接下来我们来测试一下:
package com.jianggujin.zft.job; import java.util.calendar; import org.springframework.beans.factory.initializingbean; import org.springframework.beans.factory.annotation.autowired; import org.springframework.scheduling.config.triggertask; import org.springframework.scheduling.support.crontrigger; import org.springframework.stereotype.component; import com.jianggujin.web.util.job.defaultschedulingconfigurer; public class testjob implements initializingbean { @autowired private defaultschedulingconfigurer defaultschedulingconfigurer; public void afterpropertiesset() throws exception { new thread() { public void run() { try { // 等待任务调度初始化完成 while (!defaultschedulingconfigurer.inited()) { thread.sleep(100); } } catch (interruptedexception e) { e.printstacktrace(); } system.out.println("任务调度初始化完成,添加任务"); defaultschedulingconfigurer.addtriggertask("task", new triggertask(new runnable() { @override public void run() { system.out.println("run job..." + calendar.getinstance().get(calendar.second)); } }, new crontrigger("0/5 * * * * ? "))); }; }.start(); new thread() { public void run() { try { thread.sleep(30000); } catch (exception e) { } system.out.println("重置任务............"); defaultschedulingconfigurer.resettriggertask("task", new triggertask(new runnable() { @override public void run() { system.out.println("run job..." + calendar.getinstance().get(calendar.second)); } }, new crontrigger("0/10 * * * * ? "))); }; }.start(); } }
在该类中,我们首先使用一个线程,等待我们自己的任务调度初始化完成后向其中添加一个每五秒钟打印一句话的任务,然后再用另一个线程过30秒后修改该任务,修改的本质其实是现将原来的任务取消,然后再添加一个新的任务。
在配置文件中初始化上面的类
<bean id="defaultschedulingconfigurer" class="com.jianggujin.web.util.job.defaultschedulingconfigurer"/> <bean id="testjob" class="com.jianggujin.zft.job.testjob"/>
运行程序,观察控制台输出
这样我们就实现了动态的重置任务了。以上为个人探索出来的方法,如有更好的解决方案,欢迎指正。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
上一篇: Impala 1.0 RC1发布:Spring 动态模块
下一篇: java求解集合的子集的实例