CRONTAB

CRONTAB(Task Scheduling) 
Cron is a unix, solaris utility that allows tasks to be automatically run in the background at regular intervals by the cron daemon.

crontab -e    Edit your crontab file, or create one if it doesn’t already exist.
crontab -l      Display your crontab file.
crontab -r      Remove your crontab file.
crontab -v      Display the last time you edited your crontab file.
Crontab syntax :

A crontab file has five fields for specifying day , date and time  followed by the command to be run at that interval.
*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

Notes
A. ) Repeat pattern like /2 for every 2 minutes or /10 for every 10 minutes is not supported by all operating systems. If you try to use it and crontab complains it is probably not supported.
B.) The specification of days can be made in two fields: month day and weekday. If both are specified in an entry, they are cumulative meaning both of the entries will get executed .
 
Question 1:Add a cronjob to display "HELLO WORLD"  on every 2 minutes in terminal(tty)2
 [root@localhost ~]# vim /schedule.txt
*/1 * * * * /bin/echo "HELLO WORLD" > /dev/pts/2
[root@localhost ~]# crontab /schedule.txt
[root@localhost ~]# service crond restart
Stopping crond:                                            [  OK  ]
Starting crond:                                            [  OK  ]
Press tty for check which terminal we are currently working 
[root@localhost ~]# crontab -e for show all active schedule

 
Question 2:The user robert must configure a crontab that run daily(31st december) at 15:25
local time and execute /bin/echo i got RHCE certificate 
 
[root@localhost ~]# useradd robert
[root@localhost ~]# passwd robert
Changing password for user robert.
New UNIX password:
BAD PASSWORD: it is too simplistic/systematic
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[root@localhost ~]# crontab -e -u robert

25 15 31 12 * /bin/echo "I GOT RHCE CERTIFICATE"
wq
crontab: installing new crontab
[root@localhost /]# crontab -l -u robert
25 15 31 12 * /bin/echo "I GOT RHCE CERTIFICATE" 
For remove crontab for user robert
[root@localhost /]# crontab -r -u robert
[root@localhost /]# crontab -l -u robert
no crontab for robert 
 
1. Scheduling a Job For a Specific Time
The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.
Ans: Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/ramesh/full-backup
    30 – 30th Minute
    08 – 08 AM
    10 – 10th Day
    06 – 6th Month (June)
    * – Every day of the week
2. Schedule a Job for More Than One Instance (e.g. Twice a Day)
The following script takes a incremental backup twice a day every day. This example executes the specified incremental backup shell script (incremental-backup) at 11:00 and 16:00 on every day. The comma separated value in a field specifies that the command needs to be executed in all the mentioned time.
00 11,16 * * * /home/ramesh/bin/incremental-backup
    00 – 0th Minute (Top of the hour)
    11,16 – 11 AM and 4 PM
    * – Every day
    * – Every month
    * – Every day of the week
3. Schedule a Job for Specific Range of Time (e.g. only on Weekdays)
If you wanted a job to be scheduled for every hour with in a specific range of time then use the following.Cron Job everyday during working hours. This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m
00 09-18 * * * /home/ramesh/bin/check-db-status
    00 – 0th Minute (Top of the hour)
    09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
    * – Every day
    * – Every month
    * – Every day of the week
Cron Job every weekday during working hours.This example checks the status of the database every weekday (i.e excluding Sat and Sun) during the working hours 9 a.m – 6 p.m.
00 09-18 * * 1-5 /home/ramesh/bin/check-db-status
   00 – 0th Minute (Top of the hour)
    09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
    * – Every day
    * – Every month
    1-5 -Mon, Tue, Wed, Thu and Fri (Every Weekday)

4. How to View Crontab Entries?
View Current Logged-In User’s Crontab entries.To view your crontab entries type crontab -l from your unix account as shown below.
ramesh@dev-db$ crontab -l
@yearly /home/ramesh/annual-maintenance
*/10 * * * * /home/ramesh/check-disk-space
[Note: This displays crontab of the current logged in user]
To View Root Crontab entries,Login as root user (su – root) and do crontab -l as shown below.
root@dev-db# crontab -l
no crontab for root
Crontab HowTo: View Other Linux User’s Crontabs entries.To view crontab entries of other Linux users, login to root and use -u {username} -l as shown below.
root@dev-db# crontab -u sathiya -l
@monthly /home/sathiya/monthly-backup
00 09-18 * * * /home/sathiya/check-db-status
5. How to Edit Crontab Entries?
Edit Current Logged-In User’s Crontab entries.To edit a crontab entries, use crontab -e as shown below. By default this will edit the current logged-in users crontab.
ramesh@dev-db$ crontab -e
@yearly /home/ramesh/centos/bin/annual-maintenance
*/10 * * * * /home/ramesh/debian/bin/check-disk-space
"/tmp/crontab.XXXXyjWkHw" 2L, 83C
[Note: This will open the crontab file in Vim editor for editing.Please note cron created a temporary /tmp/crontab.XX... ]
When you save the above temporary file with :wq, it will save the crontab and display the following message indicating the crontab is successfully modified.
"crontab.XXXXyjWkHw" 2L, 83C written
crontab: installing new crontab

Edit Root Crontab entries
Login as root user (su – root) and do crontab -e as shown below.
root@dev-db# crontab -e
Edit Other Linux User’s Crontab File entries.To edit crontab entries of other Linux users, login to root and use -u {username} -e as shown below.
root@dev-db# crontab -u sathiya -e
@monthly /home/sathiya/fedora/bin/monthly-backup
00 09-18 * * * /home/sathiya/ubuntu/bin/check-db-status
"/tmp/crontab.XXXXyjWkHw" 2L, 83C
6. Schedule a Job for Every Minute Using Cron.
Ideally you may not have a requirement to schedule a job every minute. But understanding this example will will help you understand the other examples mentioned below in this article.
* * * * * CMD
The * means all the possible unit — i.e. every minute of every hour through out the year. More than using this * directly, you will find it very useful in the following cases.
    When you specify */5 in minute field means every 5 minutes.
    When you specify 0-10/2 in minute field mean every 2 minutes in the first 10 minute.
    Thus the above convention can be used for all the other 4 fields.
7. Schedule a Background Cron Job For Every 10 Minutes.
Use the following, if you want to check the disk space every 10 minutes.
*/10 * * * * /home/ramesh/check-disk-space
It executes the specified command check-disk-space every 10 minutes through out the year. But you may have a requirement of executing the command only during office hours or vice versa. The above examples show how to do those things.
08. How to Disable/Redirect the Crontab Mail Output using MAIL keyword?
By default crontab sends the job output to the user who scheduled the job. If you want to redirect the output to a specific user, add or update the MAIL variable in the crontab as shown below.
ramesh@dev-db$ crontab -l
MAIL="ramesh"
@yearly /home/ramesh/annual-maintenance
*/10 * * * * /home/ramesh/check-disk-space
[Note: Crontab of the current logged in user with MAIL variable]
If you wanted the mail not to be sent to anywhere, i.e to stop the crontab output to be emailed, add or update the MAIL variable in the crontab as shown below.
MAIL=""
09. Specify PATH Variable in the Crontab
All the above examples we specified absolute path of the Linux command or the shell-script that needs to be executed.
For example, instead of specifying /home/ramesh/tape-backup, if you want to just specify tape-backup, then add the path /home/ramesh to the PATH variable in the crontab as shown below.
ramesh@dev-db$ crontab -l
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/home/ramesh
@yearly annual-maintenance
*/10 * * * * check-disk-space
[Note: Crontab of the current logged in user with PATH variable]
10. Installing Crontab From a Cron File
Instead of directly editing the crontab file, you can also add all the entries to a cron-file first. Once you have all thoese entries in the file, you can upload or install them to the cron as shown below.
ramesh@dev-db$ crontab -l
no crontab for ramesh
$ cat cron-file.txt
@yearly /home/ramesh/annual-maintenance
*/10 * * * * /home/ramesh/check-disk-space
ramesh@dev-db$ crontab cron-file.txt
ramesh@dev-db$ crontab -l
@yearly /home/ramesh/annual-maintenance
*/10 * * * * /home/ramesh/check-disk-space
Note: This will install the cron-file.txt to your crontab, which will also remove your old cron entries. So, please be careful while uploading cron entries from a cron-file.txt.
@This line executes the "ping" and the "ls" command every 12am and 12pm on the 1st day of every 2nd month. It also puts the output of the commands into the log file /var/log/cronrun.
0 0,12 1 */2 * /sbin/ping -c 192.168.0.1; ls -la >>/var/log/cronrun
@This line executes the disk usage command to get the directory sizes every 2am on the 1st through the 10th of each month. E-mail is sent to the email addresses specified with the MAILTO line. The PATH is also set to something different.
PATH=/usr/local/sbin:/usr/local/bin:/home/user1/bin
MAILTO=user1@nowhere.org,user2@somewhere.org
0 2 1-10 * * du -h --max-depth=1 /
@This line is and example of running a cron job every month, on Mondays whose dates are between 15-21. This means the third Monday only of the month at 4 a.m.
0 4 15-21 * 1 /command
@Crontab Example
A line in crontab file like below removes the tmp files from /home/someuser/tmp each day at 6:30 PM.
30     18     *     *     *         rm /home/someuser/tmp/*
@Changing the parameter values as below will cause this command to run at different time schedule below:
min  hour  day/month  month    day/week   Execution time
30   0       1            1,6,12          *             – 00:30 Hrs  on 1st of Jan, June & Dec.
0  20       *              10        1-5        –8.00 PM every weekday (Mon-Fri) only in Oct.
0  0  1,10,15    *          *   – midnight on 1st ,10th & 15th of month
5,10  0   10              *         1             – At 12.05,12.10 every Monday & on 10th of every month
Note : If you inadvertently enter the crontab command with no argument(s), do not attempt to get out with Control-d. This removes all entries in your crontab file. Instead, exit with Control-c.
@This pattern causes a task to be launched once every hour and at the fifth minute of the hour (00:05, 01:05, 02:05 etc.).
5 * * * *
@This pattern causes a task to be launched every minute during the 12th hour of Monday.
* 12 * * Mon
@This pattern causes a task to be launched every minute during the 12th hour of Monday, 16th, but only if the day is the 16th of the month.
* 12 16 * Mon
@This pattern causes a task to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and Friday. Every sub-pattern can contain two or more comma separated values.
59 11 * * 1,2,3,4,5
@This pattern is equivalent to the previous one. Value ranges are admitted and defined using the minus character.
59 11 * * 1-5
@This pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). The slash character can be used to identify periodic values, in the form of a/b. A sub-pattern with the slash character is satisfied when the value on the left divided by the one on the right gives an integer result (a % b == 0).
*/15 9-17 * * *
@This pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the16th of the month.
* 12 10-16/2 * *
@This pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th.
* 12 1-15,17,20-25 * *
Writing a crontab file can be a somewhat confusing for first time users, therefore I have listed below some crontab examples:
* * * * * <command> #Runs every minute
30 * * * * <command> #Runs at 30 minutes past the hour
45 6 * * * <command> #Runs at 6:45 am every day
45 18 * * * <command> #Runs at 6:45 pm every day
00 1 * * 0 <command> #Runs at 1:00 am every Sunday
00 1 * * 7 <command> #Runs at 1:00 am every Sunday
00 1 * * Sun <command> #Runs at 1:00 am every Sunday
30 8 1 * * <command> #Runs at 8:30 am on the first day of every month
00 0-23/2 02 07 * <command> #Runs every other hour on the 2nd of July
As well as the above there are also special strings that can be used:
@reboot <command> #Runs at boot
@yearly <command> #Runs once a year [0 0 1 1 *]
@annually <command> #Runs once a year [0 0 1 1 *]
@monthly <command> #Runs once a month [0 0 1 * *]
@weekly <command> #Runs once a week [0 0 * * 0]
@daily <command> #Runs once a day [0 0 * * *]
@midnight <command> #Runs once a day [0 0 * * *]
@hourly <command> #Runs once an hour [0 * * * *]

Multiple commands :
A double-ampersand “&&” can be used to run multiple commands consecutively. The following example would run command_01 and then command_02 once a day:
@daily <command_01> && <command_02>
$Rotate logs weekly at 12midnight. (just like the example above)
00   0    *   *   0   /usr/bin/newsyslog
$Rotate logs weekly at 12midnight. (instead of 0 for the day of the week we can use Sun for Sunday)
00   0    *   *   Sun /usr/bin/newsyslog
$Mail a report to root everyday at 11:59pm (23:59).
59   23  *    *   *   /usr/local/bin/pflogsumm -d today /var/log/maillog | mail -s "mail report" root
$Run the backup scripts at 5am on the 3rd (Wed) and 5th (Fri) day of the week. Send any errors to /dev/null
00   5   *    *   3,5 /tools/BACKUP_script.sh >> /dev/null 2>&1
$Compress backup files at 6am on the 1st and 15th of the month.
00   6   1,15 *   *   /tools/BACKUP_compress.sh
$Refresh the Squid ad blocker server list every 3 days at 12:05am.
05   0    *   *   */3 /tools/ad_servers_newlist.sh
$Clear the blocked hosts list at 3:23pm (15:23) every Monday only on even numbered months.
23   15   *   */2 1   /tools/clear_blocked_hosts.sh
$Run a script at 8:45pm (20:45) on 2nd and the 16th only in the months of January and April.
45   20   2,16 1,4 *   /tools/a_script.sh
$Run a script every day at 8:45pm (20:45) and add a random sleep time between 0 and 300 seconds.
45   20   *   *    *   sleep $(($RANDOM \% 300)); /tools/a_script.sh