Spring error Five or seven fields
Cron expression must consist of 6 fields (found 5 in "*/5 * * * *")
java.lang.IllegalStateException: Encountered invalid @Scheduled method 'run': Cron expression must consist of 6 fields (found 5 in "*/5 * * * *")java.lang.IllegalStateException: Encountered invalid @Scheduled method 'run': Cron expression must consist of 6 fields (found 7 in "0 0 12 * * ? 2027")Message produced by running the expression through org.springframework.scheduling.support.CronExpression from Spring Framework 7.0.10, the parser behind @Scheduled. 6.2.19 prints the same.
What it means
Spring’s CronExpression, which every @Scheduled(cron = …) uses, takes exactly six fields: second, minute, hour, day of month, month and day of week. Five fields is a Unix, Kubernetes or GitHub Actions expression without the seconds. Seven is usually a Quartz or EventBridge expression with a year, which Spring does not have.
Spring counts the fields after resolving its macros, so an unknown shortcut such as @reboot fails here as well, with “found 1”. Its own macros (@hourly, @daily, @weekly, @monthly, @yearly) are fine.
Rejected expressions and their fixes
Each expression opens in the tester. The message under a rejected one is what Spring Framework 7.0.10 printed for it.
-
Use0 */5 * * * *Every 5 minutes.
Every 5 minutes. Put
0in front for second 0; otherwise the fields are the same. -
Use0 0 9 * * MON-FRIAt 09:00, Monday through Friday.
Weekdays at 09:00. Spring numbers days like Unix cron, so
1-5would also work; names are clearer. -
Use0 0 12 * * *At 12:00.
Quartz with a year. Spring has no year field, so drop it and stop the task in code if it must end.
-
Use0 0 0 * * *At 00:00.
Spring has no run-at-startup cron. For that, listen for
ApplicationReadyEvent; this fix is the daily alternative.
Questions
- Does Spring accept five-field cron like Linux?
- No.
@Scheduledalways parses six fields starting with seconds. Add0in front of a five-field expression:*/5 * * * *becomes0 */5 * * * *. - Can I give Spring a Quartz expression?
- Only without the year, and check the day of week: Quartz counts Sunday as 1 and Spring as 0 or 7, so
6Lis the last Friday in Quartz and the last Saturday in Spring. - How do I turn a @Scheduled cron task off?
- Set the expression to
-, usually through a property placeholder such as@Scheduled(cron = "${jobs.report.cron:-}"). Spring treats-as a disabled trigger rather than a field count error.
Other Spring errors
- Minimum value must be less than maximum value '22-2' in cron expression "0 0 22-2 * * *"Spring: A range that runs backwards
- Invalid value for HourOfDay (valid values 0 - 23): 24 '24' in cron expression "0 0 24 * * *"Spring: A value outside the field
- For input string: "?" '?' in cron expression "0 ? * * * *"Spring: Something that is not a number
- No day-of-week before 'L' in 'L' in cron expression "0 0 0 * * L"Spring:
Lalone in day of week