我有要求以固定的时间间隔运行批处理作业,并且有能力在运行时更改此批处理作业的时间。为此,我遇到了Spring框架下提供的@Scheduled注释。但我不确定在运行时如何改变fixedDelay的值。我做了一些Google搜索,但没有发现任何有用的东西。如何在运行时更改Spring的@ Scheduled fixedDelay
回答
您可以使用Trigger
来动态设置下一个执行时间。看到这里我的答案:
Scheduling a job with Spring programmatically (with fixedRate set dynamically)
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
)。这允许您创建新的作业和触发器,并且还可以控制和监视整个计划程序。
春天开机,就可以直接使用应用程序的财产!
例如:
@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;
}
提供有关处理过程中所发生的一些信息。
谢谢,'fixedDelayString'就是我正在寻找的 – prettyvoid 2016-02-03 09:13:46
很好的答案。按照描述工作。 – flash 2016-09-06 11:45:21
@Bohemain感谢您的解决方案,但是如何在运行时更新fixedDelay? – 2016-09-27 02:53:02
- 1. Spring @Scheduled fixedDelay无法正常工作
- 2. 如何使用Spring 3.0表达式语言参数化@Scheduled(fixedDelay)?
- 3. 如何让长时间运行的@Scheduled spring方法,hibernate工作?
- 4. 使用Spring @Scheduled注释运行的方法
- 5. Spring 3.0 - @Transactional运行时更改超时
- 6. Spring @Scheduled在使用注释时执行两次任务
- 7. Spring的@Scheduled注释是如何工作的?
- 8. 运行时更改Java Spring Boot Bean
- 9. 在运行时如何在运行时更改属性值
- 10. GWT如何在运行时更改css
- 11. 如何在运行时更改persistence.xml
- 12. 如何在运行时更改图标
- 13. 如何在运行时更改sql_mode
- 14. 如何在运行时更改log4j appender?
- 15. 如何在运行时更改语言
- 16. WPF:如何在运行时更改CurrentUICulture
- 17. 如何在运行时更改iframe src?
- 18. 如何在运行时更改
- 19. 如何在运行时更改视图
- 20. 在运行时更改appconfig
- 21. 在运行时更改Winsock.LocalIP
- 22. 在运行时更改ListItem
- 23. 在运行时更改fieldCls
- 24. 更改在运行时
- 25. 在运行时更改LSApplicationQueriesSchemes
- 26. 如何停止Spring @ Scheduled排队工作
- 27. 如何更改CMFCToolBar运行时间
- 28. 如何更改Spring MVC在处理url'dot'字符时的行为
- 29. 使用javassist + spring + tomcat在运行时更改类
- 30. 如何在运行时更改静态方法的行为?
我看到你接受了最好的答案,但我仍然看到有一些未解决的问题。 NPE问题是否得到解决?是否有可能为此发布整个解决方案?欢呼 – despot 2013-11-22 09:57:52
[以编程方式用Spring调度作业(使用fixedRate动态设置)]可能的重复](http://stackoverflow.com/questions/14630539/scheduling-a-job-with-spring-programmatically-with-fixedrate-set-动态地) – 2015-10-05 09:54:14