Sub topic 2
Cron Expressions and Time Zones
Assume you know basic Spring beans, Spring Boot configuration, and Java threads. This chapter uses @Scheduled, which marks a bean method as work that Spring runs automatically.
Cron expressions and time zones
A Spring cron expression has six fields:
second minute hour day-of-month month day-of-week
For example, 0 0 2 * * * runs every day at 02:00. The zone attribute makes the intended time zone explicit.
@Component
public class ReportJobs {
@Scheduled(cron = "0 0 2 * * *", zone = "Europe/Berlin")
public void createNightlyReport() {
// Build and store the report.
}
}The time zone matters when servers run in UTC but users expect local time. Also remember that daylight-saving changes can affect local schedules.
Moving schedules into configuration
Property placeholders keep deployment choices outside the compiled code. The value after the colon is a default.
@Component
public class CleanupJob {
@Scheduled(cron = "${cleanup.cron:0 0 3 * * *}",
zone = "${cleanup.zone:UTC}")
public void deleteExpiredRecords() {
// Delete records that have expired.
}
}An environment can override cleanup.cron without rebuilding the application.
cleanup:
cron: "0 */15 * * * *"
zone: "UTC"The scheduler thread pool
Spring Boot uses one scheduler thread by default. A slow task can therefore delay unrelated tasks. Increase the pool when tasks may run independently.
spring:
task:
scheduling:
thread-name-prefix: sched-
pool:
size: 4
shutdown:
await-termination: true
await-termination-period: 30sLong-running tasks with `@Async`
@Async moves the method body to an async executor, freeing the scheduler thread. However, a later trigger can start before the previous invocation finishes. Prevent overlap with a lock or another coordination mechanism.
@Component
public class ImportJob {
@Async
@Scheduled(fixedRate = 60000)
public void importData() {
// This work may overlap with the next invocation.
}
}What happens when a task throws
For repeating scheduled tasks, Spring normally logs an uncaught exception and continues scheduling later runs. Add useful context to logs, and handle expected failures inside the method. For void @Async methods, configure an AsyncUncaughtExceptionHandler if default logging is insufficient.
Exercise
Which setting should you use for a report that must run at 02:00 in Berlin time, even when the server uses UTC?
Show answer
Use a cron expression such as "0 0 2 *" with zone = "Europe/Berlin".