Sub topic 4
Cron Expressions and Time Zones
This chapter assumes you can write a @Scheduled method with fixedRate or fixedDelay, and that scheduling is already enabled with @EnableScheduling. It covers Spring's cron format, the special characters, time zone handling, daylight saving edge cases, and the errors people hit most often.
Why use cron
fixedRate and fixedDelay count time from when the application started. They cannot say "every weekday at 08:30". A cron expression describes calendar moments instead. The task runs when the clock matches the expression, no matter when the application started.
Use cron when the requirement is phrased in calendar terms: nightly, hourly on the hour, first day of the month. Use fixedRate or fixedDelay when it is phrased as an interval: every 30 seconds.
The six-field format
Spring's @Scheduled(cron = ...) takes six fields separated by spaces.
| Position | Field | Allowed values |
|---|---|---|
| 1 | second | 0-59 |
| 2 | minute | 0-59 |
| 3 | hour | 0-23 |
| 4 | day of month | 1-31 |
| 5 | month | 1-12 or JAN-DEC |
| 6 | day of week | 0-7 or MON-SUN (0 and 7 are both Sunday) |
The first field is seconds. Classic Unix cron has five fields and starts at minutes. If you paste a five-field expression such as 0 2 * * * into Spring, it fails at startup because the expression has too few fields.
@Component
public class ReportJobs {
private static final Logger log = LoggerFactory.getLogger(ReportJobs.class);
@Scheduled(cron = "0 0 2 * * *", zone = "Europe/Berlin")
public void nightlyReport() {
log.info("cron: every day at 02:00 Berlin time");
}
}Read it field by field: second 0, minute 0, hour 2, any day of month, any month, any day of week. That is 02:00:00 every day.
Special characters
| Character | Meaning | Example | Result |
|---|---|---|---|
| `*` | every value | `0 * * * * *` | every minute, at second 0 |
| `,` | a list | `0 0 8,12,18 * * *` | at 08:00, 12:00 and 18:00 |
| `-` | a range | `0 0 9-17 * * *` | every hour from 09:00 to 17:00 |
| `/` | a step | `0 */15 * * * *` | every 15 minutes |
| `?` | no specific value | `0 0 8 ? * MON` | allowed in day fields, treated like `*` |
| `L` | last | `0 0 0 L * *` | last day of each month |
| `W` | nearest weekday | `0 0 0 15W * *` | weekday nearest the 15th |
| `#` | nth weekday | `0 0 9 ? * 5#2` | second Friday of the month |
Spring also accepts macros that replace the whole expression: @yearly, @monthly, @weekly, @daily and @hourly. For example, @Scheduled(cron = "@daily") runs at midnight.
Common expressions
| Expression | Meaning |
|---|---|
| `0 * * * * *` | every minute |
| `0 0 * * * *` | every hour on the hour |
| `0 0 8-10 * * *` | at 08:00, 09:00 and 10:00 every day |
| `0 0 6,19 * * *` | at 06:00 and 19:00 every day |
| `0 0/30 8-10 * * *` | at 08:00, 08:30, 09:00, 09:30 and 10:00 every day |
| `0 0 9-17 * * MON-FRI` | on the hour, nine to five, weekdays |
| `0 0 0 25 DEC ?` | not valid: it has only six fields counted wrongly. See the warning below. |
Count fields carefully. The last row above shows the typical mistake. 0 0 0 25 DEC ? has six tokens, but they mean second 0, minute 0, hour 0, day 25, month DEC, any weekday. That one is valid and runs at midnight on 25 December. The error to avoid is dropping the seconds field, which shifts every value one position to the left.
Step values and where they start
The / character means "start here and step by this amount". */15 and 0/15 both mean 0, 15, 30, 45 in the minute field. A step restarts at the start of each larger unit. 0 */20 * * * * fires at minutes 0, 20 and 40 of every hour, then restarts at 0. A step that does not divide evenly shows this: */25 in the minute field fires at 0 and 25 and 50, and then the gap to the next hour is 10 minutes, not 25.
For an irregular interval across hours, a cron expression cannot do it. Use fixedRate instead.
Day of month and day of week together
When you restrict both the day of month and the day of week, Spring requires both conditions to hold. 0 0 12 1 * MON means noon on the first of the month only when that day is also a Monday. Unix cron treats the two as an OR, so this is a point where Unix experience misleads. Leave one of the two fields as * or ? unless you really want the intersection.
Time zones
A cron expression names wall-clock times, so it needs a time zone to turn them into instants. Without one, Spring uses the JVM default zone, which is the server's setting. That default differs between a developer laptop, a container and a cloud region, so the same code can fire at different real moments in each.
Set the zone explicitly with the zone attribute. It takes a zone ID from the IANA database.
@Scheduled(cron = "0 0 9 * * MON-FRI", zone = "America/New_York")
public void marketOpenSummary() {
// 09:00 New York time on weekdays, in every environment
}Prefer region IDs such as Europe/Berlin over fixed offsets such as GMT+1. A region ID knows about daylight saving rules. A fixed offset does not, so the job drifts by an hour for part of the year.
If you want UTC, write zone = "UTC". UTC has no daylight saving, which makes it the simplest choice for technical jobs such as cleanup. Use a business zone for jobs that are tied to people's working days.
An invalid zone ID fails when the application context starts. That is useful, because a typo never reaches production silently.
Daylight saving transitions
Two days a year, the local clock does not behave normally. Take Europe/Berlin.
- Spring forward (last Sunday of March): the clock jumps from 02:00 to 03:00. The local time 02:30 does not exist that day. A job set for
0 30 2 * * *is skipped on that date, and runs the next day as usual. - Fall back (last Sunday of October): the clock goes from 03:00 back to 02:00, so local times between 02:00 and 03:00 occur twice. Spring computes the next fire time from the previous one and does not run a job twice for the repeated hour. For hourly or more frequent expressions, such as
0 0 * * * *, the schedule follows the real timeline in that repeated hour.
The practical rule: do not schedule important daily jobs between 02:00 and 03:00 in a zone that observes daylight saving. Pick 04:00, or use UTC.
Reading the next run time
You can check an expression before deploying it. CronExpression is part of Spring Framework and has the same syntax as the @Scheduled attribute.
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.springframework.scheduling.support.CronExpression;
public class CronCheck {
public static void main(String[] args) {
CronExpression cron = CronExpression.parse("0 0 2 * * *");
ZonedDateTime from = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
ZonedDateTime next = cron.next(from);
for (int i = 0; i < 3; i++) {
System.out.println(next);
next = cron.next(next);
}
}
}The program prints the next three 02:00 moments in Berlin. CronExpression.parse throws IllegalArgumentException for an invalid expression, and next returns null if no future date matches, for example 0 0 0 30 FEB *. The time zone comes from the ZonedDateTime you pass in, so the check uses the same zone you plan to put in zone.
This also makes cron logic testable without waiting for the clock. A later chapter covers testing scheduled tasks in general.
Cron with property placeholders
The cron attribute accepts placeholders, which lets each environment choose its schedule. The next chapter covers this fully. One value is special: the string - (the constant Scheduled.CRON_DISABLED) disables the trigger. Setting cleanup.cron=- in a test profile turns the job off without removing the annotation.
@Scheduled(cron = "${cleanup.cron:0 0 3 * * *}", zone = "UTC")
public void cleanup() {
// delete expired records
}Common errors
| Symptom | Likely cause |
|---|---|
| `IllegalStateException` or `IllegalArgumentException` at startup, saying the expression must consist of 6 fields | A five-field Unix expression was used |
| The job runs every second | The seconds field is `*`, as in `* * * * * *` or `* 0 2 * * *` |
| The job runs at the wrong hour on the server | No `zone` set, and the server zone is not what you assumed |
| The job never runs | The date combination cannot occur, or the day-of-month and day-of-week fields conflict |
| The job runs an hour off for part of the year | A fixed offset was used instead of a region ID |
| Two runs overlap | The previous run took longer than the interval and a pool with several threads was used |
The second row deserves attention. * 0 2 * * * looks like "every day at 02:00", but with the seconds field set to * it fires every second from 02:00:00 to 02:00:59. Always put a concrete value, usually 0, in the first field.
Diagram
Exercises
Exercise
Write a Spring cron expression that runs a task at 18:30 on the last day of every month, in the Asia/Tokyo zone, and give the full annotation.
Show answer
@Scheduled(cron = "0 30 18 L ", zone = "Asia/Tokyo"). The fields are second 0, minute 30, hour 18, day of month L (last day), any month, any weekday.
Exercise
A job uses cron = "0 30 2 *" and zone = "Europe/Berlin". On the last Sunday of March it did not run. Why, and how would you change the schedule so it runs every day?
Show answer
At 02:00 that day the Berlin clock jumps to 03:00, so 02:30 does not exist and the run is skipped. Move the job to an hour that always exists, such as 04:30, or schedule it in UTC with zone = "UTC".
Exercise
A teammate wrote @Scheduled(cron = " 15 9 * MON-FRI") to run once at 09:15 on weekdays. What does it actually do, and what is the fix?
Show answer
Because the seconds field is , it fires every second from 09:15:00 to 09:15:59 on weekdays, 60 times. The fix is "0 15 9 * MON-FRI".