什么是动态定时任务:是由客户制定生成的,服务端只知道该去执行什么任务,但任务的定时是不确定的(是由客户制定)。这样总不能修改配置文件每定制个定时任务就增加一个trigger吧,即便允许客户修改配置文件,但总需要重新启动web服务啊,研究了下Quartz在Spring中的动态定时,发现<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean" > <property name="jobDetail" ref="schedulerJobDetail"/> <property name="cronExpression"> <value>0/10 * * * * ?</value> </property> 中cronExpression是关键,如果可以动态设置cronExpression的值,也就说如果我们可以直接调用CronTriggerBean中设置cronExpression的方法,就可以顺利解决问题了。熟悉1的朋友可以跳过不看,下面2、3是动态定时任务的具体实现。1. Quartz在Spring中的简单配置Spring配置文件: <bean id="schedulerJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="scheduleInfoAction"/> <property name="targetMethod" value="simpleJobTest"/> <property name="concurrent" value="false"/> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean" > <property name="jobDetail" ref="schedulerJobDetail"/> <property name="cronExpression"> <value>0/10 * * * * ?</value> </property> </bean> <bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref local="cronTrigger"/> </list> </property></bean>在上面的配置中设定了① targetMethod: 指定需要定时执行scheduleInfoAction中的simpleJobTest()方法② concurrent:对于相同的JobDetail,当指定多个Trigger时, 很可能第一个job完成之前,第二个job就开始了。指定concurrent设为false,多个job不会并发运行,第二个job将不会在第一个job完成之前开始。③ cronExpression:0/10 * * * * ?表示每10秒执行一次,具体可参考附表。④ triggers:通过再添加其他的ref元素可在list中放置多个触发器。scheduleInfoAction中的simpleJobTest()方法注意:此方法没有参数,如果scheduleInfoAction有两个方法simpleJobTest()和simpleJobTest(String argument),则spring只会去执行无参的simpleJobTest().public void simpleJobTest() { log.warn("uh oh, Job is scheduled !'" + "' Success..."); }2.Quartz在Spring中动态设置cronTrigger方法一Spring配置文件:<bean id="scheduleInfoAction" class="com.lively.happyoa.jobs.webapp.action.ScheduleInfoAction"> <property name="scheduler" ref="schedulerFactory"/> <property name="scheduleInfoManager" ref="scheduleInfoManager"/> </bean> <bean id="schedulerJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="scheduleInfoAction"/> <property name="targetMethod" value="reScheduleJob"/> <property name="concurrent" value="false"/> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean" > <property name="jobDetail" ref="schedulerJobDetail"/> <property name="cronExpression"> <value>0/10 * * * * ?</value> </property> </bean> <bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref local="cronTrigger"/> </list> </property></bean>scheduleInfoAction中的reScheduleJob ()方法及相关方法① reScheduleJob读取数据库,获得自定义定时器调度时间(): private void reScheduleJob() throws SchedulerException, ParseException { // 运行时可通过动态注入的scheduler得到trigger CronTriggerBean trigger = (CronTriggerBean) scheduler.getTrigger( "cronTrigger", Scheduler.DEFAULT_GROUP); String dbCronExpression = getCronExpressionFromDB(); String originConExpression = trigger.getCronExpression(); // 判断从DB中取得的任务时间(dbCronExpression)和现在的quartz线程中的任务时间(originConExpression)是否相等 // 如果相等,则表示用户并没有重新设定数据库中的任务时间,这种情况不需要重新rescheduleJob if(!originConExpression.equalsIgnoreCase(dbCronExpression)){ trigger.setCronExpression(dbCronExpression); scheduler.rescheduleJob("cronTrigger", Scheduler.DEFAULT_GROUP, trigger); } // 下面是具体的job内容,可自行设置 // executeJobDetail();}② getCronExpressionFromDB():从数据库中获得dbCronExpression的具体代码,由于使用了scheduleInfoManager,所以要在定义相应的setter方法 private String getCronExpressionFromDB(){ String sql="from ScheduleInfo scheduleInfo where 1=1 "; sql=sql+" and scheduleInfo.infoId = '"+"1" + "'"; List scheduleList = scheduleInfoManager.queryScheduleInListBySql(sql); ScheduleInfo scheduleInfo = (ScheduleInfo)scheduleList.get(0); String dbCronExpression = scheduleInfo.getCronExpression(); return dbCronExpression;}③ 在spring配置文件的scheduleInfoAction配置了相应的property(scheduler/ scheduleInfoManager),要为其设置setter方法 private Scheduler scheduler; // 设值注入,通过setter方法传入被调用者的实例scheduler public void setScheduler(Scheduler scheduler) { this.scheduler = scheduler; } private ScheduleInfoManager scheduleInfoManager; // 设值注入,通过setter方法传入被调用者的实例scheduleInfoManager public void setScheduleInfoManager(ScheduleInfoManager scheduleInfoManager){ this.scheduleInfoManager = scheduleInfoManager; }3. Quartz在Spring中动态设置cronTrigger方法二在上面的2中我们可以看到,尽管已经可以动态进行rescheduleJob了,不过依然需要我们设置一个cronExpression,如果尝试一下拿掉spring配置中的 <property name="cronExpression"> <value>0/10 * * * * ?</value> </property>则容器(如tomcat)启动时会报错。实际中我们希望tomcat启动时就可以直接去读数据库,拿到相应的dbCronExpression,然后定时执行一个job,而不希望配置初始的cronExpression ,观察下面的CronTriggerBean,考虑到cronExpression需要初始化,如果设定一个类InitializingCronTrigger继承CronTriggerBean,然后在这个类中做一些读取DB的初始化工作(设置cronExpression),问题就可以解决了。Spring配置文件:<bean id="scheduleInfoAction" class="com.lively.happyoa.jobs.webapp.action.ScheduleInfoAction"> <property name="scheduler" ref="schedulerFactory"/> <property name="scheduleInfoManager" ref="scheduleInfoManager"/> </bean> <bean id="schedulerJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="scheduleInfoAction"/> <property name="targetMethod" value="reScheduleJob"/> <property name="concurrent" value="false"/> </bean> <bean id="cronTrigger" class="com.lively.happyoa.jobs.webapp.action.ScheduleInfoAction.InitializingCronTrigger"> <property name="jobDetail" ref="schedulerJobDetail"/> <!--<property name="cronExpression"> <value>0/10 * * * * ?</value> </property>--> <property name="scheduleInfoManager" ref="scheduleInfoManager"/> </bean> <bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref local="cronTrigger"/> </list> </property></bean>InitializingCronTrigger中的相关方法注意:在注入scheduleInfoManager属性的时候,我们可以去读取DB任务时间(之所以放在setter方法中,是因为需要在设置scheduleInfoManager后进行getCronExpressionFromDB(),否则,也可以①②逻辑把放在类的构造函数中).注意InitializingCronTrigger必须extends CronTriggerBean.public class InitializingCronTrigger extends CronTriggerBean implements Serializable { private ScheduleInfoManager scheduleInfoManager; // 设值注入,通过setter方法传入被调用者的实例scheduleInfoManager public void setScheduleInfoManager(ScheduleInfoManager scheduleInfoManager){ this.scheduleInfoManager = scheduleInfoManager; // 因为在getCronExpressionFromDB使用到了scheduleInfoManager,所以 // 必须上一行代码设置scheduleInfoManager后进行getCronExpressionFromDB String cronExpression = getCronExpressionFromDB (); // ① // 因为extends CronTriggerBean ,此处调用父类方法初始化cronExpression setCronExpression(cronExpression); // ②} private String getCronExpressionFromDB(){ String sql="from ScheduleInfo scheduleInfo where 1=1 "; sql=sql+" and scheduleInfo.infoId = '"+"1" + "'"; List scheduleList = scheduleInfoManager.queryScheduleInListBySql(sql); ScheduleInfo scheduleInfo = (ScheduleInfo)scheduleList.get(0); String dbCronExpression = scheduleInfo.getCronExpression(); return dbCronExpression;}……}附表:"0 0 12 * * ?" 每天中午12点触发
"0 15 10 ? * *" 每天上午10:15触发
"0 15 10 * * ?" 每天上午10:15触发
"0 15 10 * * ? *" 每天上午10:15触发
"0 15 10 * * ? 2005" 2005年的每天上午10:15触发
"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发
"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发
"0 15 10 15 * ?" 每月15日上午10:15触发
"0 15 10 L * ?" 每月最后一日的上午10:15触发
"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发
至于每个符号 看看例子就好了.很简单了.
package com.sundoctor.quartz.service;
import java.text.ParseException;
import java.util.Date;
import java.util.UUID;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("schedulerService")
public class SchedulerServiceImpl implements SchedulerService {
private Scheduler scheduler;
private JobDetail jobDetail;
@Autowired
public void setJobDetail(@Qualifier("jobDetail") JobDetail jobDetail) {
this.jobDetail = jobDetail;
}
@Autowired
public void setScheduler(@Qualifier("quartzScheduler") Scheduler scheduler) {
this.scheduler = scheduler;
}
@Override
public void schedule(String cronExpression) {
schedule(null, cronExpression);
}
@Override
public void schedule(String name, String cronExpression) {
try {
schedule(name, new CronExpression(cronExpression));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
@Override
public void schedule(CronExpression cronExpression) {
schedule(null, cronExpression);
}
@Override
public void schedule(String name, CronExpression cronExpression) {
if (name == null || name.trim().equals("")) {
name = UUID.randomUUID().toString();
}
try {
scheduler.addJob(jobDetail, true);
CronTrigger cronTrigger = new CronTrigger(name, Scheduler.DEFAULT_GROUP, jobDetail.getName(),
Scheduler.DEFAULT_GROUP);
cronTrigger.setCronExpression(cronExpression);
scheduler.scheduleJob(cronTrigger);
scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, cronTrigger);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
@Override
public void modifyTime(String name,String time)
{
try {
Trigger trigger = scheduler.getTrigger(name, Scheduler.DEFAULT_GROUP);
if (trigger != null && trigger instanceof CronTrigger)
{
System.out.println("modify time");
CronTrigger cronTrigger = (CronTrigger)trigger;
//scheduler.unscheduleJob(name, Scheduler.DEFAULT_GROUP);
//scheduler.pauseTrigger(name, Scheduler.DEFAULT_GROUP);
//schedule(name,time);
cronTrigger.setCronExpression(time);
// scheduler.resumeTrigger(name, Scheduler.DEFAULT_GROUP);
scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, cronTrigger);
System.out.println("modify success");
}
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void schedule(Date startTime) {
schedule(startTime, null);
}
@Override
public void schedule(String name, Date startTime) {
schedule(name, startTime, null);
}
@Override
public void schedule(Date startTime, Date endTime) {
schedule(startTime, endTime, 0);
}
@Override
public void schedule(String name, Date startTime, Date endTime) {
schedule(name, startTime, endTime, 0);
}
@Override
public void schedule(Date startTime, Date endTime, int repeatCount) {
schedule(null, startTime, endTime, 0);
}
@Override
public void schedule(String name, Date startTime, Date endTime, int repeatCount) {
schedule(name, startTime, endTime, 0, 0L);
}
@Override
public void schedule(Date startTime, Date endTime, int repeatCount, long repeatInterval) {
schedule(null, startTime, endTime, repeatCount, repeatInterval);
}
@Override
public void schedule(String name, Date startTime, Date endTime, int repeatCount, long repeatInterval) {
if (name == null || name.trim().equals("")) {
name = UUID.randomUUID().toString();
}
try {
scheduler.addJob(jobDetail, true);
SimpleTrigger SimpleTrigger = new SimpleTrigger(name, Scheduler.DEFAULT_GROUP, jobDetail.getName(),
Scheduler.DEFAULT_GROUP, startTime, endTime, repeatCount, repeatInterval);
scheduler.scheduleJob(SimpleTrigger);
scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, SimpleTrigger);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
}