How to setup Cron Jobs
Cron Jobs
What are Cron Jobs? A cron job is a command or a series of commands set to run at specific times on your Linux or Unix based system. Cron jobs are very flexible when used in conjuction with programs and shell scripts and can automate various parts of system administration (.such as logfile rotation, program execution, gather system information and sending emails etc.)
Summary of Commands
crontab filename - Install filename as your crontab file.
crontab -e - Edit your crontab file.
crontab -l - Show your crontab file.
crontab -r - Remove your crontab file.
Creating a Cron job
To Create a cron job, run the command
crontab -e
This will open the crontab for the user and allow you to create a cron job following the syntax below:
Syntax Your cron job looks like as follows: 1 2 3 4 5 /path/to/command arg1 arg2 Where, 1: Minute (0-59) 2: Hours (0-23) 3: Day (0-31) 4: Month (0-12 [12 == December]) 5: Day of the week(0-7 [7 or 0 == sunday]) /path/to/command - Script or command name to schedule Same above five fields structure can be easily remembered with following diagram: * * * * * command to be executed - - - - - | | | | | | | | | —– Day of week (0 - 7) (Sunday=0 or 7) | | | ——- Month (1 - 12) | | ——— Day of month (1 - 31) | ———– Hour (0 - 23) ————- Minute (0 - 59)Insert non-formatted text here
This Example cronjob is set to run every minute and execute the omgiambreakingtheserver.sh script. Note the actual example in relation to the syntax above.
[root@training-linux yum]# crontab -l */1 * * * * /script/omgiambreakingtheserver.sh
Another set of examples as shown in the man page:
EXAMPLE CRON FILE
# use /bin/sh to run commands, no matter what /etc/passwd says
SHELL=/bin/sh
# mail any output to âpaulâ, no matter whose crontab this is
MAILTO=paul
#
# run five minutes after midnight, every day
5 0 * * * $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
# run at 2:15pm on the first of every month -- output mailed to paul
15 14 1 * * $HOME/bin/monthly
# run at 10 pm on weekdays, annoy Joe
0 22 * * 1-5 mail -s "Itâs 10pm" joe%Joe,%%Where are your kids?%
23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"
5 4 * * sun echo "run at 5 after 4 every sunday"