Handling repetitive tasks on Linux can be simplified with the powerful Cron utility. This guide will teach you everything you need to know about Cron, from setting up your first cron job to mastering advanced scheduling techniques. By the end of this guide, you’ll be able to use Cron to automate tasks efficiently.
Cron is a time-based job scheduler in Unix-like operating systems. It allows users to schedule commands or scripts to run at specific intervals, such as every minute, hour, day, week, or month. Cron jobs are defined in a file called crontab.
A cron job is defined by five time-and-date fields followed by the command to be executed:
* * * * * command
- - - - -
| | | | |
| | | | |
| | | | +---- Day of the week (0 - 7) (Sunday=0 or 7)
| | | +------ Month (1 - 12)
| | +-------- Day of the month (1 - 31)
| +---------- Hour (0 - 23)
+------------ Minute (0 - 59)
Open the Crontab File: To edit the cron jobs, use:
crontab -e
2. Add a Cron Job: Example: To run a script every day at midnight:
0 0 * * * /path/to/your/script.sh
Save and Exit: Save the file and exit the text editor.
Running a Backup Script Daily at 2 AM:
0 2 * * * /path/to/backup_script.sh
2. Clearing a Log File Weekly:
0 0 * * 0 echo "" > /var/log/your_log_file.log
3. Sending Email Notifications Monthly:
0 9 1 * * /path/to/send_email.sh
Multiple Times per Day: To run a job every 15 minutes:
*/15 * * * * /path/to/command
2. Specific Days of the Week: To run a job every Monday, Wednesday, and Friday at noon:
0 12 * * 1,3,5 /path/to/command
3.Combining Time Fields: To run a job at 6:30 AM every day:
30 6 * * * /path/to/command
List Scheduled Cron Jobs: To view all your scheduled cron jobs, use:
crontab -l
2. Remove a Cron Job: To remove all cron jobs, use:
crontab -r
To remove a specific job, edit the crontab file and delete the corresponding line.
Cron Job Not Running:
Check the cron service status:
sudo service cron status
chmod +x /path/to/script.sh
2. Log and Debug Output: Redirect output to a log file for troubleshooting:
0 0 * * * /path/to/command >> /path/to/logfile.log 2>&1
By mastering the crontab syntax and understanding how to schedule, manage, and troubleshoot cron jobs, you can automate repetitive tasks on your Linux system. Practice creating and managing cron jobs to become proficient with this powerful utility.