CRONTAB
Crontab (short for "cron table") is a configuration file in Unix-like operating systems that specifies shell commands to run periodically on a given schedule.
The commands are executed by the cron daemon, a system process that runs in the background. Crontab allows users to automate repetitive tasks such as backups, updates, and scheduled maintenance.
Components of Crontab
Each line in the crontab file consists of two parts:
- Timing information: Specifies when the command should run.
- Command: The shell command to execute.
The timing information is divided into five fields:
- Minute (0-59)
- Hour (0-23)
- Day of the month (1-31)
- Month (1-12)
- Day of the week (0-7, where both 0 and 7 represent Sunday)
Note: The fields can be filled with numbers, ranges, lists, or special characters like
*
, which means "every" value for that field.Crontab Format:
* * * * * command_to_run
| | | | |
| | | | +---- Day of the week (0-7)
| | | +------ Month (1-12)
| | +-------- Day of the month (1-31)
| +---------- Hour (0-23)
+------------ Minute (0-59)
Special Characters:
*
: Every value (e.g., every minute, every hour).,
: Separate multiple values (e.g.,1,15,30
means at the 1st, 15th, and 30th minute).-
: Specify a range (e.g.,1-5
means from 1 to 5)./n
: Specify intervals (e.g.,*/5
means every 5 minutes).
Managing Crontab:
1. Edit a crontab file: crontab -e
This opens the crontab file for the current user in an editor.
2. List scheduled tasks (view crontab entries): crontab -l
3. Remove a user's crontab: crontab -r
Example Crontab Entries:
1. Run a backup script every day at 3:00 AM:
0 3 * * * /path/to/backup.sh
2. Run a system update every Sunday at 2:30 AM:
30 2 * * 7 sudo apt-get update -y
3. Run a script every 15 minutes:
*/15 * * * * /path/to/script.sh
4. Send a reminder email at 9 AM on weekdays (Monday to Friday):
0 9 * * 1-5 echo "Reminder: Submit your report!" | mail -s "Daily Reminder" user@example.com
Special Scheduling Keywords
@reboot
: Run the command once at startup.@daily
or@midnight
: Run the command once every day (midnight).@hourly
: Run the command every hour.@weekly
: Run the command once every week (Sunday at midnight).@monthly
: Run the command once every month (on the 1st at midnight).@yearly
or@annually
: Run the command once a year (January 1st at midnight).
Example of Special Keywords:
- To run a script at system boot:
@reboot /path/to/startup.sh
Comments
Post a Comment