2013-03-06 120 views
19

我有要求以固定的时间间隔运行批处理作业,并且有能力在运行时更改此批处理作业的时间。为此,我遇到了Spring框架下提供的@Scheduled注释。但我不确定在运行时如何改变fixedDelay的值。我做了一些Google搜索,但没有发现任何有用的东西。如何在运行时更改Spring的@ Scheduled fixedDelay

+0

我看到你接受了最好的答案,但我仍然看到有一些未解决的问题。 NPE问题是否得到解决?是否有可能为此发布整个解决方案?欢呼 – despot 2013-11-22 09:57:52

+0

[以编程方式用Spring调度作业(使用fixedRate动态设置)]可能的重复](http://stackoverflow.com/questions/14630539/scheduling-a-job-with-spring-programmatically-with-fixedrate-set-动态地) – 2015-10-05 09:54:14

回答

17

您可以使用Trigger来动态设置下一个执行时间。看到这里我的答案:

Scheduling a job with Spring programmatically (with fixedRate set dynamically)

+0

正是我在找的东西 - 谢谢队友 – jsf 2013-03-06 16:43:55

+0

仅供参考 - 留下了对代码中发现的'NullPointerException'错误的评论。 – jsf 2013-03-06 17:03:20

+0

有没有办法在睡眠中断当前的触发器并改变它的值。 – jsf 2013-03-06 17:53:11

2

AFAIK Spring API不会让你访问你需要更改触发器的内部。但是,你可以改为手动配置豆类:

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> 
    <property name="jobDetail" ref="jobDetail" /> 
    <property name="startDelay" value="10000" /> 
    <property name="repeatInterval" value="50000" /> 
</bean> 

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
    <property name="triggers"> 
     <list> 
      <ref bean="simpleTrigger" /> 
     </list> 
    </property> 
</bean> 

然后作为记录在SchedulerFactoryBean来:

在运行时的工作动态注册,使用一个bean参考 这个SchedulerFactoryBean来去直接访问Quartz Scheduler (org.quartz.Scheduler)。这允许您创建新的作业和触发器,并且还可以控制和监视整个计划程序。

33

春天开机,就可以直接使用应用程序的财产!

例如:

@Scheduled(fixedDelayString = "${my.property.fixed.delay.seconds}000") 
private void process() { 
    // your impl here 
} 

请注意,还可以在情况下,没有定义属性的默认值,例如,以具有“60”的一默认值(秒):

@Scheduled(fixedDelayString = "${my.property.fixed.delay.seconds:60}000") 

其他的事情,我发现:

  • 方法必须是void
  • 方法必须没有参数
  • 方法可以是private

我发现能够使用private知名度得心应手,以这种方式使用它:

@Service 
public class MyService { 
    public void process() { 
     // do something 
    } 

    @Scheduled(fixedDelayString = "${my.poll.fixed.delay.seconds}000") 
    private void autoProcess() { 
     process(); 
    } 
} 

private,计划的方法可以是本地服务,而不是您的服务API的一部分。

此外,此方法允许process()方法返回一个值,该方法可能不会。例如,您的process()方法可以看起来像:

public ProcessResult process() { 
    // do something and collect information about what was done 
    return processResult; 
} 

提供有关处理过程中所发生的一些信息。

+0

谢谢,'fixedDelayString'就是我正在寻找的 – prettyvoid 2016-02-03 09:13:46

+0

很好的答案。按照描述工作。 – flash 2016-09-06 11:45:21

+1

@Bohemain感谢您的解决方案,但是如何在运行时更新fixedDelay? – 2016-09-27 02:53:02