gpt4 book ai didi

java - 为 Spring @Scheduled 提供时区?

转载 作者:IT老高 更新时间:2023-10-28 13:04:45 29 4
gpt4 key购买 nike

如何为基于 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com