How can I configure the time zone for a Spring based @Scheduled cron job?
Background:
I have a job that executes once a day, say 2 PM, using Spring's @Scheduled
annotation:
@Scheduled(cron = "0 0 14 * * *")
public void execute() {
// do scheduled job
}
The problem is that 2 PM differs between different servers, because Spring uses on TimeZone.getDefault()
internally. Moreover, the JavaDoc of TimeZone.getDefault()
states that:
Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation.
In other words, the time zone is not determined. It may depend on JVM implementation, server time zone configuration, server location, and / or other unknown factors. Consequently, the cron job triggers on different times on different servers, unless there is a way to explicitly set which time zone that should be used?
I am using Spring 3.2.2.
Update
As of Spring 4, Spring Jira issue SPR-10456 has been resolved. Consequently, the @Scheduled
annotation has a new zone attribute for exactly this purpose.
I doubt you want different jobs or parts of application to use different time zones. Assuming you want to have it all consistent and DRY, either configure OS on all servers to have consistent time zone, or set user.timezone Java system property for all of the application servers. Centrally manage configuration (OS, application server), and for that puppet and chef can be very useful.
There is element
zone
in annotation@Scheduled
, starting from version 4.0.You can insert a timezone as a string that can be accepted by
java.util.TimeZone
.It turned out that I could not use the
@Scheduled
annotation, but I implemented a work-around. In the JavaDoc of the SchedulingConfigurer it is stated that:Next, I changed the cron job to implement the
Runnable
interface and then updated my configuration file to implement theSchedulingConfigurer
, see below:Please read the JavaDoc of the @EnableScheduling for more information.
Update
As of Spring 4, Spring Jira issue SPR-10456 has been resolved. Consequently, the
@Scheduled
annotation has a new zone attribute for exactly this purpose.