让程序修改Quartz定时执行的时间,灵活执行Schedule。 先看Spring配置 <bean id="target" class="cn.com.jastar.test.quartz.BussinessBean" /> <bean id="schedulerJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="target"></property> <property name="targetMethod" value="test"></property> <property name="concurrent" value="false"></property> </bean> <bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="schedulerJobDetail" /> <property name="cronExpression"> <!-- 默认13:05执行 --> <value>0 05 13 * * ?</value> </property> </bean> </list> </property> </bean> <bean id="scheduleConfigManager" class="cn.com.jastar.test.quartz.ScheduleConfigManager"> <property name="scheduler" ref="schedulerFactory" /> </bean> 业务方法test执行打印当前执行时间。 public class BussinessBean { public void test() { System.out.println("Target methed execute at " + Calendar.getInstance().getTime().toLocaleString()); } } ScheduleConfigManager类重新设置Schedule,通过修改触发器表达式trigger.setCronExpression和重新scheduler.rescheduleJob来完成。 public class ScheduleConfigManager { /** * 重新设置表达式 * * @param newExpression * @throws SchedulerException * @throws ParseException */ public void reScheduleJob(String newExpression) throws SchedulerException, ParseException { try { CronTriggerBean trigger = (CronTriggerBean)scheduler.getTrigger("cronTrigger", Scheduler.DEFAULT_GROUP); String originConExpression = trigger.getCronExpression(); if (!originConExpression.equalsIgnoreCase(newExpression)) { trigger.setCronExpression(newExpression); scheduler.rescheduleJob("cronTrigger", Scheduler.DEFAULT_GROUP, trigger); } } catch (java.text.ParseException e) { e.printStackTrace(); } } private Scheduler scheduler; // 设值注入,通过setter方法传入被调用者的实例scheduler public void setScheduler(Scheduler scheduler) { this.scheduler = scheduler; } public Scheduler getScheduler() { return scheduler; } } 来看测试方法 public static void main(String[] args) { XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("quarts.xml")); ScheduleConfigManager manager = (ScheduleConfigManager)factory.getBean("scheduleConfigManager"); try { // 休息两分钟 Thread.sleep(2000 * 60); // 修改为13:10执行 manager.reScheduleJob("0 10 13 * * ?"); } catch (ParseException e) { e.printStackTrace(); } catch (SchedulerException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } 结果当然符合我们的预期 Target methed execute at 2010-11-17 13:05:00 Target methed execute at 2010-11-17 13:10:00