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配置:
[code]
<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>
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值