Cron is a powerful and widely used Linux utility for scheduling repetitive tasks to run automatically at specified times or intervals. It allows users and administrators to automate system maintenance, backups, monitoring scripts, and other routine operations without manual intervention.
How Cron Works
Cron works by using the cron daemon (crond), a background process that runs continuously and checks defined schedules to determine when tasks should be executed.
Each user can maintain a personalized crontab file, which contains a list of scheduled commands or scripts to run automatically at specified times.
In addition to user-specific crontabs, Linux also supports a system-wide crontab, usually located at /etc/crontab, along with directories such as /etc/cron.d/, where administrators can configure and manage scheduled system-level tasks.
The Crontab File Syntax
Each line in a crontab defines a task with the following format:
* * * * * command_to_execute
- - - - -
| | | | |
| | | | +---- Day of the week (0-6 or Sun-Sat)
| | | +------ Month (1-12 or Jan-Dec)
| | +-------- Day of the Month (1-31)
| +---------- Hour (0-23)
+------------ Minute (0-59)Use an asterisk (*) to denote “every” for a field. You can specify ranges (1-5), lists (1,2,5), or step values (*/10 means every 10 units).
Common Examples
Managing Your Crontab
The following list explains how users can manage their crontab using built-in Linux commands. These operations are essential for automation and system administration.
1. View crontab entries:
crontab -l2. Edit crontab for current user:
crontab -eThis opens the crontab file in your default editor.
3. Remove current user crontab:
crontab -rExample Cron Job
To run a backup script every day at 2:30 AM, add this line to your crontab:
30 2 * * * /home/user/backup.shEnsure the script has executable permissions (chmod +x backup.sh) and that you use absolute paths for commands within the script.
Special Strings for Scheduling
Special scheduling keywords in cron provide clarity and ease of use. The list below outlines these standard execution intervals.
1. @reboot: Run once at system startup.
2. @hourly: Run once every hour.
3. @daily or @midnight: Run once a day at midnight.
4. @weekly: Run once a week.
5. @monthly: Run once a month.
6. @yearly or @annually: Run once a year.
Example:
@reboot /home/user/startup_script.shOutput Handling
By default, cron sends the output and errors to the user’s email.
* * * * * /path/to/script.sh >> /path/to/logfile.log 2>&1Troubleshooting Cron Jobs
1. Verify cron service is running:
sudo systemctl status crond2. Check logs (e.g., /var/log/cron, /var/log/syslog) for cron activity.
3. Use absolute paths for all executable commands in cron jobs.
4. Use scripts with proper permissions and test them manually before scheduling.