Spring cron vs normal cron?
Spring cron is a feature of the Spring framework. It enables precise scheduling of tasks within your Java applications down to the second. The defining of tasks is as easy as using the @Scheduled
annotation.
Spring cron: 0 0 9 * * ?
(runs at 9 AM daily)
UNIX cron: 0 9 * * *
(runs at 9 AM daily)
The configuration of a task in Spring is as follows:
While Spring cron offers Application context awareness and springs up to the expectations of Java developers, UNIX cron schedules tasks at the system level.
Spring and Unix cron: The fields of dreams (and nightmares)
Every Spring cron pattern follows a 6-field format, and every Unix cron abides by a 5-field format. Knowing their differences is crucial.
Spring cron example: 0 15 10 * * 1-5
- translates to 10:15AM, Monday to Friday.
UNIX cron example: 15 10 * * 1-5
- same schedule, but doesn't care about seconds.
Remember: Always follow the zero policy in the seconds field for Spring patterns, and Spring despises the 7th 'year' field. That's so last year! 💁♀️
Don't brass your cron expressions
When crafting Spring cron expressions, you can use day aliases such as "MON-FRI"
for clarity. For instance, "0 0 18 * * 1-5" becomes "0 0 18 * * MON-FRI".
Words of caution for spring cron expressions:
- Spring cron isn't a fan of the 7th 'year' field. Use it and prepare for a boot time exception.
- Turn to Spring-specific documentation, such as
CronSequenceGenerator
for getting your Spring cron right. Dry documentation, but it gets the job done. - Be wary of online cron tools. They may give you incorrect advice for Spring cron.
Deploying crons in the wild
Now that we know the differences, let's see some practical applications.
- Hourly tasks
- Spring cron:
"0 0 */1 * * *"
- This one ticks every hour, on the hour. - UNIX cron:
"0 */1 * * *"
- Close, but not as precise.
- First Sunday of the month
- Spring cron:
"0 0 0 ? * SUN#1"
- This bird chirps at midnight every first Sunday. - UNIX cron: Well, UNIX cron is sleeping on Sundays.
- Every 8 hours
- Spring cron:
"0 0 */8 * * *"
- This one goes off like clockwork: 12 AM, 8 AM, and 4 PM. - UNIX cron:
"0 */8 * * *"
- Good try, but no second precision.
In each scenario, Spring cron proves to be more flexible accommodating for more complex scheduling needs.
References
Was this article helpful?