java - 为 Spring @Scheduled 提供时区?

标签 java spring cron timezone scheduling

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

相关文章:

javascript - org.springframework.web.bind.MissingServletRequestParameterException : Required Long parameter 'userId' is not present"错误

spring - 向所有存储库添加自定义行为,无需 xml 配置

php 脚本在浏览器中运行时有效,但在运行 cron 事件时无效

java - 关闭tomcat时停止计划的计时器

java - 警告 : Activity not started, 它的当前任务已被带到最前面

java - mysql 存储过程与 hsqldb 存储过程

bash - 有没有办法在 ubuntu 18 的 crontab 作业脚本中使用 .envrc

java - 带有文件名的子类中出现奇怪的错误

java - 使用类构造函数创建 2 种不同类型的对象数组

shell - 选择性抑制输出保留退出代码