java 如何在 CronTrigger (quartz 2.2, spring 4.1) 中更改 cron 表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25737992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:34:38  来源:igfitidea点击:

How to change cron expression in CronTrigger (quartz 2.2, spring 4.1)

javaspringcronquartz-scheduler

提问by Dima

I'm a bit stuck migrating to latest quartz 2.2 and spring 4.1... Here's a cron trigger, I omit the job and other fluff for clarity:

我在迁移到最新的石英 2.2 和 spring 4.1 时有点卡住了……这是一个 cron 触发器,为了清楚起见,我省略了工作和其他绒毛:

...
       <bean id="timeSyncTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
         <property name="jobDetail" ref="timeSyncJob"/>
         <property name="startDelay" value="10000"/>
         <property name="cronExpression" value="0 0 1 * * ? *"/>
       </bean>
...

Now, I need to change its cronExpressionat run time, and it's not as simple as I thought. I can't reference the bean and change the property because its a factory giving CronTriggerinterface which in turn doesn't have setCronExpressionmethod any longer, it has become immutable. Before I could simply fish out a trigger from the context and set its new cron expression. It worked very well for many years, until the upgrade become unavoidable.

现在,我需要在运行时更改它的cronExpression,并没有我想象的那么简单。我无法引用 bean 并更改属性,因为它是一个提供CronTrigger接口的工厂,而该接口又不再具有setCronExpression方法,它已变得不可变。在我可以简单地从上下文中找出触发器并设置其新的 cron 表达式之前。多年来,它一直运行良好,直到升级变得不可避免。

So, how do we accomplish this simple task today? Totally lost in documentations and versions.. Thanks in advance!

那么,我们今天如何完成这个简单的任务呢?完全丢失在文档和版本中.. 提前致谢!

采纳答案by ivan.sim

回答by Markus Pscheidt

In addition to the CronTriggerFactoryBeanyou probably have a SchedulerFactoryBean, which provides access to the Quartz scheduler as well as the CronTrigger. The Quartz scheduler allows you to reschedule a job with a new/modified trigger:

除了CronTriggerFactoryBean您可能有一个SchedulerFactoryBean,它提供对 Quartz 调度程序以及 CronTrigger 的访问。Quartz 调度器允许您使用新的/修改的触发器重新调度作业:

@Autowired private SchedulerFactoryBean schedulerFactoryBean;
...
public void rescheduleCronJob() {

    String newCronExpression = "..."; // the desired cron expression

    Scheduler scheduler = schedulerFactoryBean.getScheduler();
    TriggerKey triggerKey = new TriggerKey("timeSyncTrigger");
    CronTriggerImpl trigger = (CronTriggerImpl) scheduler.getTrigger(triggerKey);
    trigger.setCronExpression(newCronExpression );
    scheduler.rescheduleJob(triggerKey, trigger);
}