How to Write a Crontab Entry in Linux
This guide provides a comprehensive overview of the crontab syntax used for scheduling automated tasks in the Linux operating system. It details the five time-and-date fields, explains how to use special operators for advanced scheduling, outlines common shortcut strings, and provides real-world examples to help you configure your cron jobs accurately.
The Basic Crontab Syntax
A standard crontab entry consists of five time-and-date fields followed by the command to execute:
* * * * * command_to_execute
- - - - -
| | | | |
| | | | +----- Day of the week (0 - 6) (Sunday to Saturday, 7 is also Sunday)
| | | +------- Month of the year (1 - 12)
| | +--------- Day of the month (1 - 31)
| +----------- Hour of the day (0 - 23)
+------------- Minute of the hour (0 - 59)
The Five Time Fields
- Minute (0 - 59): Specifies the exact minute the command runs.
- Hour (0 - 23): Specifies the hour in 24-hour format (e.g., 0 = midnight, 13 = 1 PM).
- Day of Month (1 - 31): Specifies the calendar day.
- Month (1 - 12): Specifies the month of the year (1 = January, 12 = December).
- Day of Week (0 - 7): Specifies the day of the week.
Both
0and7represent Sunday.
Special Characters (Operators)
You can use specific operators to define complex scheduling intervals within any field:
- Asterisk (
*): Represents all possible values. An asterisk in the minute field means "run every minute." - Comma (
,): Specifies a list of values. For example,1,15,30in the minute field runs the task at minutes 1, 15, and 30. - Hyphen (
-): Specifies an inclusive range of values. For example,1-5in the day-of-week field runs the task Monday through Friday. - Slash (
/): Specifies step values within a range. For example,*/15in the minute field runs the task every 15 minutes.
Crontab Shorthand Strings
Cron supports predefined shortcuts that can replace the five-field format:
@reboot— Runs once at system startup.@yearlyor@annually— Runs once a year at midnight on January 1 (0 0 1 1 *).@monthly— Runs once a month at midnight on the first day (0 0 1 * *).@weekly— Runs once a week at midnight on Sunday (0 0 * * 0).@dailyor@midnight— Runs once a day at midnight (0 0 * * *).@hourly— Runs once an hour at the start of the hour (0 * * * *).
Practical Examples
Run a backup script every day at 2:30 AM:
30 2 * * * /usr/local/bin/backup.shRun a task every 10 minutes:
*/10 * * * * /usr/bin/python3 /opt/scripts/monitor.pyRun a script at 8:00 AM on the first day of every month:
0 8 1 * * /home/user/scripts/report.shRun a job every Monday and Thursday at 6:00 PM:
0 18 * * 1,4 /var/scripts/sync.sh
Managing Crontab Files
Use the crontab utility to manage your user
schedule:
crontab -e— Edit the current user's crontab file using the default text editor.crontab -l— Display the current user's crontab entries.crontab -r— Remove all crontab entries for the current user.