如何为基于 Spring 的系统配置时区@预定 http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-scheduled计划任务?
背景:
我有一个每天执行一次的工作,比如下午 2 点,使用 Spring@Scheduled
注解:
@Scheduled(cron = "0 0 14 * * *")
public void execute() {
// do scheduled job
}
问题是不同服务器之间的 2 PM 不同,因为 Spring 使用TimeZone.getDefault()
内部 https://github.com/SpringSource/spring-framework/blob/3.2.x/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java#L81。此外,JavaDoc http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getDefault() of TimeZone.getDefault()
指出:
获取该主机的默认时区。默认时区的来源可能因实现而异。
换句话说,时区是不确定的。它可能取决于 JVM 实现、服务器时区配置、服务器位置和/或其他未知因素。因此,cron 作业会在不同服务器上的不同时间触发,除非有办法明确设置应使用哪个时区?
我正在使用 Spring 3.2.2。
Update
从 Spring 4 开始,Spring Jira 问题SPR-10456 https://jira.spring.io/browse/SPR-10456已经解决了。因此,@Scheduled
注释有一个新的zone http://docs.spring.io/spring-framework/docs/4.0.x/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html#zone--属性正是为了这个目的。
结果发现我无法使用@Scheduled
注释,但我实现了一个解决方法。在 JavaDoc 中调度配置器 http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/scheduling/annotation/SchedulingConfigurer.html据称:
[SchedulingConfigurer is] 通常用于设置执行计划任务时要使用的特定 TaskScheduler bean,或以编程方式注册计划任务,而不是使用 @Scheduled 注释的声明性方法。
接下来,我更改了 cron 作业来实施Runnable
接口,然后更新我的配置文件以实现SchedulingConfigurer
, 见下文:
@Configuration
@EnableScheduling
@ComponentScan("package.that.contains.the.runnable.job.bean")
public class JobConfiguration implements SchedulingConfigurer {
private static final String cronExpression = "0 0 14 * * *";
private static final String timeZone = "CET";
@Autowired
private Runnable cronJob;
@Bean
CronTrigger cronTrigger() {
return new CronTrigger(cronExpression, TimeZone.getTimeZone(timeZone));
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addCronTask(new CronTask(job, cronTrigger()));
}
}
请阅读 JavaDoc@EnableScheduling http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html了解更多信息。
Update
从 Spring 4 开始,Spring Jira 问题SPR-10456 https://jira.spring.io/browse/SPR-10456已经解决了。因此,@Scheduled
注释有一个新的zone http://docs.spring.io/spring-framework/docs/4.0.x/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html#zone--属性正是用于此目的,例如
@Scheduled(cron = "0 0 14 * * *", zone = "CET")
public void execute() {
// do scheduled job
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)