Crontab
Job Automation with Crontab
We can schedule tasks and automate them using crontab.
Editing Crontab
To schedule jobs, we need to edit the crontab file:
nano /etc/crontab
Examples
Run a script every day at midnight
0 0 * * * /path/to/script.sh
Example Use Case:
Automate database backups daily at midnight.
Run a script every Monday at 8 AM
0 8 * * 1 /path/to/script.sh
Example Use Case:
Send weekly reports every Monday morning.
Run a script every 5 minutes
*/5 * * * * /path/to/script.sh
Example Use Case:
Monitor server health by running a script every 5 minutes.
Run a script at 3:30 PM on the first day of every month
30 15 1 * * /path/to/script.sh
Example Use Case:
Generate and send monthly invoices on the first of every month.
Run a script every Sunday at 10 PM as a specific user
0 22 * * 0 username /path/to/script.sh
Example Use Case:
Perform a full system cleanup every Sunday night.
Understanding Crontab Syntax
A cron job follows this format:
MIN HOUR DOM MON DOW USER COMMAND
- MIN → Minute (0 - 59)
- HOUR → Hour (0 - 23)
- DOM → Day of the Month (1 - 31)
- MON → Month (1 - 12)
- DOW → Day of the Week (0 - Sunday, 6 - Saturday)
- USER → The user who runs the command
- COMMAND → The script or command to execute
Listing and Managing Cron Jobs
List current user's cron jobs
crontab -l
Edit the crontab for the current user
crontab -e
Remove all scheduled jobs for the current user
crontab -r
Logs and Debugging
To check logs for cron jobs, use:
cat /var/log/syslog | grep CRON
By using crontab, we can automate repetitive tasks and ensure they run at scheduled intervals.