How to use Crontab in Linux ?
The crontab in linux runs tasks in the background at specific times; it’s like the Task Scheduler on Windows. Add tasks to your system’s crontab files using the appropriate syntax and cron will automatically run them for you.
Crontab files can be used to automate backups, system maintenance and other repetitive tasks.
# crontab -e
Use this command to open your user account’s crontab file. Commands in this file run with your user account’s permissions.
# sudo crontab -e
If you want a command to run with system permissions, use the sudo crontab -e command to open the root account’s crontab file. Use the su -c “crontab -e” command instead if your Linux distribution doesn’t use sudo
Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
Lines in the crontab file are written in the following sequence, with the following acceptable values:
minute(0–59) hour(0–23) day(1–31) month(1–12) weekday(0–6) command
30 11 * * * python /home/ubuntu/dump.py
Above cron job run 11:30 AM everyday.
*/15 * * * * sh /home/ec2-use/backup.sh
Above cron job run backup.sh script at every 15 minutes.
* * 5,15,20,25 * * rsync -azh /home/hemant/umservice/* /app/web/umservice
Above cron synchronize files from source directory to destination directory on date of month 5,15,20,25.
* * * * 1-5 sh /home/ravikant/mysqldump.sh
Above cron run mysqldump script Monday to Friday.
30 3 * * 0,6 sh /app/automation/deploy.sh
Above cron run script on sunday, saturday at 3:30 AM
00 17 * * * sh /usr/local/bin/rti-openports >> /var/log/rti-ports.log
Create a job that runs every Monday at 5:00 PM and executes the script /usr/local/bin/rti-openports. Redirect STDOUT and STDERR to /var/log/rti-ports.log.
# crontab -l
List all cron job which is scheduled for the current logged user.
# crontab -u ravikant -l
List crontab for specific user.
@daily sh /home/ravi/script.sh
This crontab run daily.
# tail /var/log/cron
To view last 10 cron log.