The name "Cron" is derived from the Greek word "Chronos," meaning time.
A Cron expression is a string expression used to specify the execution time of scheduled tasks. It consists of 6 fields representing seconds, minutes, hours, days of the month, months, and days of the week.
Each field can use specific symbols to specify time ranges or intervals.
┌──────────── [optional] seconds (0 - 59)
| ┌────────── minute (0 - 59)
| | ┌──────── hour (0 - 23)
| | | ┌────── day of month (1 - 31)
| | | | ┌──── month (1 - 12) OR jan,feb,mar,apr ...
| | | | | ┌── day of week (0 - 6, sunday=0) OR sun,mon ...
| | | | | |
* * * * * * command
Apart from the basic numeric ranges, Cron expressions also support some special symbols and characters:
-
Asterisk (*): Represents any value. For example, * in the minute field means it executes every minute.
-
Comma (,): Used to separate multiple values. For example, 1,3,5 in the hour field means it executes at 1 o'clock, 3 o'clock, and 5 o'clock.
-
Slash (/): Used to specify intervals. For example, */5 in the minute field means it executes every 5 minutes.
-
Hyphen (-): Used to specify a range. For example, 10-20 in the date field means it executes from the 10th to the 20th.
-
Question mark (?): Only used in the day of the month and day of the week fields, it represents no specific value. It is usually used to avoid conflicts.
Some examples of Cron expression:
-
0 0 12 * * ?
: execute at 12:00 PM every day.
-
0 0/5 * * * ?
: execute every 5 minutes.
-
0 0 8-18 ? * MON-FRI
: execute every hour between 8:00 AM and 6:00 PM from Monday to Friday.
Cron expressions are very flexible and can meet the requirements of various scheduled tasks.
However, it is important to note that Cron expressions can only represent fixed points in time and cannot handle complex time logic.
If more complex scheduling tasks are needed, it may be necessary to use specialized scheduling frameworks or libraries.