Spring Top

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:


1. Overview

Cron expressions enable us to schedule tasks to run periodically at a specific date and time. After its introduction in Unix, other Unix-based operating systems and software libraries (including the Spring Framework) adopted its approach for task scheduling.

In this quick tutorial, we're going to see what's the difference between Cron expressions in Unix-based operating systems and the Spring Framework.

2. Unix Cron

Cron in most Unix-based systems has five fields: minute (0-59), hour (0-23), day of the month (1-31), months (1-12 or names), and day of the week (0-7 or names).

We can put some special values in each field, like an asterisk (*):

5 0 * * *

The job will be executed 5 minutes after midnight every day. It's also possible to use a range of values:

5 0-5 * * *

Here the scheduler will execute the task 5 minutes after midnight, and also 5 minutes after 1, 2, 3, 4, and 5 o'clock every day.

Or, we can use a list of values:

5 0,3 * * *

Now the scheduler executes the job five minutes after midnight and five minutes after 3 o'clock every day. The original Cron expression offers many more features than what we covered so far.

However, it comes with one big limitation: We can't schedule jobs with second precision since it doesn't have a dedicated second field.

Let's see how Spring manages to fix this limitation.

3. Spring Cron

To schedule periodic background tasks in Spring, we usually pass a Cron expression to the @Scheduled annotation.

As opposed to Cron expressions in Unix-based systems, the Cron expression in Spring has six space-separated fields: second, minute, hour, day, month, and weekday.

For instance, to run a task every ten seconds we can do:

*/10 * * * * *

Also, to run a task every 20 seconds from 8 am to 10m every day:

*/20 * 8-10 * * *

As shown in the above examples, the first field represents the second portion of the expression. That's the difference between the two implementations. Despite the difference in the second field, Spring supports many features from the original Cron such as range numbers or lists.

From the implementation's perspective, the CronSequenceGenerator class is responsible for parsing the Cron expressions in Spring.

4. Conclusion

In this short tutorial, we saw the Cron implementation difference between Spring and most Unix-based systems. Along the way, we saw a few examples of both implementations.

In order to see more examples of Cron expressions, it's highly recommended to check out our Guide to Cron Expressions. Moreover, taking a look at the source code of the CronSequenceGenerator class can give us a good idea of how Spring implements this feature.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Comments are closed on this article!