quartz动态更新运行时间

    @Resource
    private Scheduler startQuertz;//这个需要注入过来
    
    /**
     * 更新定时任务的运行时间
     * @param triggerKey 定时任务在spring里配置bean的id
     * @param cronExpression 定时器的cron表达式
     * @param executeNow 默认值为0,不要立即执行定时任务一次; 非0值表示立即执行一次
     * @return
     */
    public boolean updateCronExpression(String triggerKey, String cronExpression, Integer executeNow) {
    	if(StringUtils.isBlank(triggerKey) || StringUtils.isBlank(cronExpression)) {
    		log.error("参数错误");
    		return false;
    	}
    	if(executeNow == null) {
    		executeNow = 0;
    	}
    	triggerKey = triggerKey.trim();
    	cronExpression = cronExpression.trim();
    	
		TriggerKey key = new TriggerKey(triggerKey);//动态条件
		
		try {
			Trigger oldTrigger = startQuertz.getTrigger(key);
			
			if(oldTrigger instanceof CronTriggerImpl) {
    			CronTriggerImpl trigger = (CronTriggerImpl)oldTrigger;
    			trigger.setCronExpression(cronExpression);//动态传入的条件
    			//不立即执行
    			if(executeNow.intValue() == 0) {
    				trigger.setStartTime(new Date());//防止立即生效
    			}
    			startQuertz.rescheduleJob(trigger.getKey(), trigger);   				
			}

		} catch (Exception e) {
			log.error("更新cron定时任务运行时间失败[triggerKey=" + triggerKey + "]:", e);
			return false;
		}
    	return true;
    }


xml配置:
<bean id="demoTrigger"
      class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    <property name="jobDetail">
        <bean class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <property name="targetObject" ref="jobObj"/>
            <property name="targetMethod" value="jobObj的方法名"/>
        </bean>
    </property>
    <property name="cronExpression" value="0 0 3 * * ?"/>
</bean>
<!-- 配置线程池 -->
<bean id="taskExecutor"
      class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <!-- 线程池维护线程的最少数量 -->
    <property name="corePoolSize" value="5"/>
    <!-- 线程池维护线程所允许的空闲时间 -->
    <property name="keepAliveSeconds" value="30000"/>
    <!-- 线程池维护线程的最大数量 -->
    <property name="maxPoolSize" value="1000"/>
    <!-- 线程池所使用的缓冲队列 -->
    <property name="queueCapacity" value="200"/>
</bean>
<!--如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" lazy-init="true" autowire="no" 
    class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="taskExecutor" ref="taskExecutor"/>
    <property name="triggers">
        <list>
            <ref bean="demoTrigger"/>
        </list>
    </property>
</bean>

猜你喜欢

转载自sd-zyl.iteye.com/blog/2224989