Introduction
Cron is a time-based job scheduler in Unix-like operating systems. It is used to schedule scripts or commands to run at specified intervals. This guide covers the installation, configuration, and management of cron jobs.
Installation and Setup
-
Update Package List
sudo apt update
-
Install Cron
sudo apt install cron
-
Enable Cron Service
sudo systemctl enable cron
Basic Cron Syntax
Cron jobs are configured in the crontab file and follow this syntax:
minute hour day_of_month month day_of_week command_to_run
- minute: 0-59
- hour: 0-23
- day_of_month: 1-31
- month: 1-12 or JAN-DEC
- day_of_week: 0-6 or SUN-SAT
Example Cron Job
To run a command at 5:30 PM every Tuesday:
30 17 * * 2 curl http://www.google.com && echo "DONE"
Common Cron Schedules
* * * * *
- Run the command every minute.12 * * * *
- Run the command 12 minutes past every hour.0,15,30,45 * * * *
- Run the command every 15 minutes.*/15 * * * *
- Run the command every 15 minutes.0 4 * * *
- Run the command every day at 4:00 AM.0 4 * * 2-4
- Run the command every Tuesday, Wednesday, and Thursday at 4:00 AM.20,40 */8 * 7-12 *
- Run the command on the 20th and 40th minute of every 8th hour during the last 6 months of the year.
Managing Cron Jobs
-
Edit User Crontab
crontab -e
-
Edit System-Wide Crontab
sudo nano /etc/crontab
-
List User Crontab Jobs
crontab -l
-
Remove All User Crontab Jobs
crontab -r
-
Edit Crontab for a Specific User
sudo crontab -u user -e
Cron Job Shortcuts
Cron also supports several shortcut notations for common schedules:
@hourly
- Equivalent to0 * * * *
@daily
- Equivalent to0 0 * * *
@weekly
- Equivalent to0 0 * * 0
@monthly
- Equivalent to0 0 1 * *
@yearly
- Equivalent to0 0 1 1 *
Conclusion
Cron jobs are a powerful way to automate tasks on a Linux system. By understanding the syntax and utilizing the various management commands, you can efficiently schedule and manage tasks to run at specific intervals.
This documentation guide provides a clear and comprehensive overview of cron jobs, including installation, configuration, and management commands. It includes practical examples and common usage scenarios to help you effectively use cron on your Linux system.