如何为基于 Spring 的 @Scheduled cron 作业配置时区?
背景:
我有一个工作每天执行一次,比如下午 2 点,使用 Spring 的 @Scheduled
注释:
@Scheduled(cron = "0 0 14 * * *")
public void execute() {
// do scheduled job
}
问题在于不同服务器之间的下午 2 点不同,因为 Spring 在 TimeZone.getDefault()
internally 上使用。此外,TimeZone.getDefault()
的 JavaDoc 声明:
Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation.
也就是说,时区是不确定的。它可能取决于 JVM 实现、服务器时区配置、服务器位置和/或其他未知因素。因此,cron 作业在不同服务器上的不同时间触发,除非有办法明确设置应该使用哪个时区?
我使用的是 Spring 3.2.2。
更新
从 Spring 4 开始,Spring Jira 问题 SPR-10456 已得到解决。因此,@Scheduled
注释有一个新的 zone 属性来实现这个目的。
最佳答案
原来我不能使用 @Scheduled
注释,但我实现了一个变通方法。在 SchedulingConfigurer 的 JavaDoc 中指出:
[SchedulingConfigurer is] Typically used for setting a specific TaskScheduler bean to be used when executing scheduled tasks or for registering scheduled tasks in a programmatic fashion as opposed to the declarative approach of using the @Scheduled annotation.
接下来,我更改了 cron 作业以实现 Runnable
接口(interface),然后更新我的配置文件以实现 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()));
}
}
请阅读 @EnableScheduling 的 JavaDoc 了解更多信息。
更新
从 Spring 4 开始,Spring Jira 问题 SPR-10456 已得到解决。因此,@Scheduled
注释有一个新的 zone 属性来实现这个目的,例如
@Scheduled(cron = "0 0 14 * * *", zone = "CET")
public void execute() {
// do scheduled job
}
关于java - 为 Spring @Scheduled 提供时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15930171/