Linux job scheduling with crontab

We previously looked into scheduling jobs with at command now we will look into using crontab to execute commands in the future time.


Canada colocation

First we will need to make sure cron is installed. On Red Hat or CentOS we can execute following command. If the packages do not exist we will need to install cron package.

# yum list installed | grep cron
cronie.x86_64                   1.4.11-11.el7                          @anaconda
cronie-anacron.x86_64           1.4.11-11.el7                          @anaconda
crontabs.noarch                 1.11-6.20121102git.el7                 @anaconda

and to install it

yum install cronie crontabs -y

Crontables for users are located in the /var/spool/cron directory. Lets look at what happens when we create user and this user creates cron job and then we delete it as root.

 

#useradd test
# su test
$ crontab -e
no crontab for test - using an empty one
crontab: installing new crontab   (add a test job to crontab 30 1 * * * /bin/ls)
$ exit
exit
# ls /var/spool/cron/
test
# rm test 
rm: remove regular file ‘test’? y
# su test
$ crontab -e
no crontab for test - using an empty one

The other place where system crontables are stored is /etc/cron.d and only root has access to this folders.

Crontab command

This command is used to edit, list and remove crontables.

(-e) deit

(-l) list

(-r) remove

(-u) modify different users cron

 

File /etc/crontab specifies the syntax for this command

# cat /etc/crontab 
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# 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

Examples

#run this crontab entry every 5 minutes
*/5 * * * * /usr/local/bin/test.sh
#run this crontab at 6:30am
30 6 * * * /usr/local/bin/test.sh
#run this crontab Apr 02 at 6 15
15 06 02 Apr * /usr/local/bin/test.sh
#run every Monday at 9 and 11
0 9,11 * * Mon /usr/local/bin/test.sh
#run every Monday from 9am to 3pm on the hour
0 9-15 * * Mon /usr/local/bin/test.sh
#run every week day at 10 30 pm
30 22 * * Mon,Tue,Wed,Thu,Fri /usr/local/bin/test.sh