There are occasions when you want to create a schedule tasks on your server. Suppose you want to backup your hard drive once a week, or you want to run a script at 6 am every morning. All those things that you want to run at specific interval can be set with cron job. The cron daemon is a long running process that executes commands at user specified intervals. This howto provides a step-by-step tutorial on how you can schedule such a task using a program named crontab.
Setting up crontab is very easy. To edit your crontab file use the following command
If default editor is not defined then you will see an error message:
/bin/sh: /bin/vi: No such file or directory OR crontab: "/bin/vi" exited with status 12
So do the command:
Now, vim will be used as the default editor. You may use any editor of your choice here(nano etc.).
The pattern is easy:
* * * * command/tobe/executed
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
Suppose you want to run a shell script every hour
0 * * * * /root/script.sh
Run a command every 10 minutes
*/10 * * * * command
Run a command at 5 am in Morning
0 5 * * * command
Run a command every weekend 2am
0 2 * * 5-7 command
Run a command every saturday
0 2 * * sat command
Disable Email Output
By default crontab returns emails the root with the output of the cron, you might want to avoid it.
Just pipe all the output to the null device, also known as the black hole. On Unix-like operating systems,/dev/null is a special file that discards all data written to it.
0 * * * * /root/script.sh > /dev/null 2>&1
You can define a MAILTO variable to output the mail to a particular email address.
But this MAILTO will output the result of all the cronjobs. Suppose you want to get the result of 1 cronjob. You can do it using mailx. Make sure mailx is installed.
yum install mailx #For Fedora/Centos
apt-get install mailx #For Ubuntu
*/10 * * * * /root/script.sh 2>&1 | mail -s "Output From Cron Job" email@example.com
Erase all the Crontab jobs by using
Cronjob provide eight special strings that can also be used to make the file look more readable
@reboot Run at startup
@hourly Run at "0 1 1 * *"
@daily Run at "0 0 * * *"
@midnight Run at "0 0 * * *"
@weekly Run at "0 0 * * 0"
@monthy Run at "0 0 1 * *"
@yearly Run at "0 0 1 1 *"
@annually Run at "0 0 1 1 *"