Chapter 4: Linux Advanced Commands
4.9 Scheduling tasks: cron
In short: cron runs commands automatically on a schedule.
cron runs commands automatically on a schedule. Edit your table with crontab -e, list with crontab -l.
┌──────── minute (0-59)
│ ┌────── hour (0-23)
│ │ ┌──── day of month (1-31)
│ │ │ ┌── month (1-12)
│ │ │ │ ┌ day of week (0-7, 0 and 7 = Sunday)
│ │ │ │ │
* * * * * command
| Schedule | Meaning |
|---|---|
*/5 * * * * |
Every 5 minutes |
0 2 * * * |
Every day at 02:00 |
30 9 * * 1-5 |
09:30 Monday to Friday |
0 0 1 * * |
Midnight on the 1st of every month |
@reboot |
Once at every boot |
Now open your terminal and try this with me. Example — back up the website every night at 1:30 AM. Run crontab -e and add this line:
30 1 * * * tar -czf $HOME/backups/site-$(date +\%F).tar.gz /var/www/html
(% has a special meaning in crontab, so it is written as \%. Create the folder first with mkdir -p ~/backups.)
cron on Amazon Linux 2023
AL2023 does not ship cron by default. Install it: sudo yum install -y cronie, then sudo service crond start and sudo systemctl enable crond. (systemd timers are the modern alternative.) The server clock is UTC by default — set India time with sudo timedatectl set-timezone Asia/Kolkata.
Ravindra Bagale's Tip
Before scheduling any cron job, run the exact command manually first and check it works. Cron runs with a very small PATH and no interactive shell, so always use full paths (/usr/bin/tar, /home/ubuntu/backup.sh) and redirect output to a log file: >> /home/ubuntu/backup.log 2>&1. Keep this in mind!
Ravindra Bagale's Tip – मराठी
कोणताही cron job schedule करण्याआधी तीच command आधी हाताने चालवून ती चालते का ते तपासा. Cron खूप छोट्या PATH सोबत आणि interactive shell शिवाय चालतो, म्हणून नेहमी full paths वापरा (/usr/bin/tar, /home/ubuntu/backup.sh) आणि output log file मध्ये redirect करा: >> /home/ubuntu/backup.log 2>&1. हे लक्षात ठेवा!
Ravindra Bagale's Tip – हिंदी
कोई भी cron job schedule करने से पहले वही command पहले खुद हाथ से चलाकर देखो कि वह काम करती है. Cron बहुत छोटे PATH के साथ और बिना interactive shell के चलता है, इसलिए हमेशा full paths लिखो (/usr/bin/tar, /home/ubuntu/backup.sh) और output को log file में redirect करो: >> /home/ubuntu/backup.log 2>&1. यह याद रखना!