Wednesday, June 27, 2001

How do I add cron job under Linux or UNIX like operating system?

Cron job are used to schedule commands to be executed periodically. You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, and /etc/cron.*/ directories. It also checks the /var/spool/cron/ directory.

crontab command
Root privileges Yes
Requirements crond
crontab is the command used to install, deinstall or list the tables (cron configuration file) used to drive the cron(8) daemon in Vixie Cron. Each user can have their own crontab file, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. You need to use crontab command for editing or setting up your own cron jobs.
Types of cron configuration files

There are different types of configuration files:

  1. The UNIX / Linux system crontab : Usually, used by system services and critical jobs that requires root like privileges. The sixth field (see below for field description) is the name of a user for the command to run as. This gives the system crontab the ability to run commands as any user.
  2. The user crontabs: User can install their own cron jobs using the crontab command. The sixth field is the command to run, and all commands run as the user who created the crontab

How Do I install or create or edit my own cron jobs?
To edit your crontab file, type the following command at the UNIX / Linux shell prompt:
$ crontab -e
Syntax of crontab (field description)
The syntax is:
1 2 3 4 5 /path/to/command arg1 arg2
OR
1 2 3 4 5 /root/backup.sh
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
Easy to remember format:

1 2 3 4 5 USERNAME /path/to/command arg1 arg2
OR
1 2 3 4 5 USERNAME /path/to/script.sh
1: Minute (0 - 59)
2: Hour (0 - 23)
3: Day of month (1 - 31)
4: Month (1 - 12)
5: Day of week (0 - 7) (Sunday=0 or 7)

How do I use operators?
An operator allows you to specifying multiple values in a field. There are three operators:

  1. The asterisk (*) : This operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.
  2. The comma (,) : This operator specifies a list of values, for example: "1,5,10,15,20, 25".
  3. The dash (-) : This operator specifies a range of values, for example: "5-15" days , which is equivalent to typing "5,6,7,8,9,....,13,14,15" using the comma operator.
  4. The separator (/) : This operator specifies a step value, for example: "0-23/" can be used in the hours field to specify command execution every other hour. Steps are also permitted after an asterisk, so if you want to say every two hours, just use */2.
More examples
#To run /path/to/command five minutes after midnight, every day, enter:
5 0 * * * /path/to/command

#Run /path/to/script.sh at 2:15pm on the first of every month, enter:
15 14 1 * * /path/to/script.sh

#Run /scripts/phpscript.php at 10 pm on weekdays, enter:
0 22 * * 1-5 /scripts/phpscript.php

#Run /root/scripts/perl/perlscript.pl at 23 minutes after midnight, 2am, 4am ..., everyday, enter:
23 0-23/2 * * * /root/scripts/perl/perlscript.pl

# Run /path/to/unixcommand at 5 after 4 every Sunday, enter:
5 4 * * sun /path/to/unixcommand

# Execute a cron job every 5 Minutes
*/5 * * * * /home/ramesh/backup.sh

# Execute a cron job every 5 Hours
0 */5 * * * /home/ramesh/backup.sh

# Execute a job every 5 Seconds
$ cat every-5-seconds.sh
#!/bin/bash
while true
do
 /home/ramesh/backup.sh
 sleep 5
done
Now, execute this shell script in the background using nohup as shown below. This will keep executing the script even after you logout from your session. This will execute your backup.sh shell script every 5 seconds.
$ nohup ./every-5-seconds.sh &

# Execute a job every 5th weekday
# The following example runs the backup.sh every Friday at midnight.
0 0 * * 5 /home/ramesh/backup.sh
(or)
0 0 * * Fri /home/ramesh/backup.sh
You can either user number or the corresponding three letter acronym for the weekday as shown below. [0=Sun, 1=Mon, 2=Tue, 3=Wed, 4=Thu, 5=Fri, 6=Sat]

# Execute a job every 5 months
0 0 1 5,10 * /home/ramesh/backup.sh
(or)
0 0 1 May,Oct * /home/ramesh/backup.sh


How do I disable email output?
By default the output of a command or a script (if any produced), will be email to your local email account. To stop receiving email output from crontab you need to append >/dev/null 2>&1. For example:
0 3 * * * /root/backup.sh >/dev/null 2>&1
To mail output to particular email account let us say vivek@nixcraft.in you need to define MAILTO variable as follows:
MAILTO="vivek@nixcraft.in"
0 3 * * * /root/backup.sh >/dev/null 2>&1

See "Disable The Mail Alert By Crontab Command" for more information.

Task: List all your cron jobs
Type the following command:
# crontab -l
# crontab -u username -l

To remove or erase all crontab jobs use the following command:
# Delete the current cron jobs #
crontab -r

## Delete job for specific user. Must be run as root user ##
crontab -r -u username

Instead of the first five fields, you can use any one of eight special strings. It will not just save your time but it will improve readability. Special string Meaning
@reboot Run once, at startup.
@yearly Run once a year, "0 0 1 1 *".
@annually (same as @yearly)
@monthly Run once a month, "0 0 1 * *".
@weekly Run once a week, "0 0 * * 0".
@daily Run once a day, "0 0 * * *".
@midnight (same as @daily)
@hourly Run once an hour, "0 * * * *".

Examples
#Run ntpdate command every hour:
@hourly /path/to/ntpdate
#Make a backup everyday:
@daily /path/to/backup/script.sh

More about /etc/crontab file and /etc/cron.d/* directories
/etc/crontab is system crontabs file. Usually only used by root user or daemons to configure system wide jobs. All individual user must must use crontab command to install and edit their jobs as described above. /var/spool/cron/ or /var/cron/tabs/ is directory for personal user crontab files. It must be backup with users home directory.

Understanding Default /etc/crontab
Typical /etc/crontab file entries:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
First, the environment must be defined. If the shell line is omitted, cron will use the default, which is sh. If the PATH variable is omitted, no default will be used and file locations will need to be absolute. If HOME is omitted, cron will use the invoking users home directory.

Additionally, cron reads the files in /etc/cron.d/ directory. Usually system daemon such as sa-update or sysstat places their cronjob here. As a root user or superuser you can use following directories to configure cron jobs. You can directly drop your scripts here. The run-parts command run scripts or programs in a directory via /etc/crontab file:

Directory Description
/etc/cron.d/ Put all scripts here and call them from /etc/crontab file.
/etc/cron.daily/ Run all scripts once a day
/etc/cron.hourly/ Run all scripts once an hour
/etc/cron.monthly/ Run all scripts once a month
/etc/cron.weekly/ Run all scripts once a week
How do I use above directories to put my own scripts or jobs?

Here is a sample shell script called clean.cache. This script is created to clean up cached files every 10 days. This script is directly created at /etc/cron.daliy/ directory. In other words create a text file called /etc/cron.daily/clean.cache as follows.
#!/bin/bash
# A sample shell script to clean cached file from lighttpd web server
CROOT="/tmp/cachelighttpd/"

# Clean files every $DAYS
DAYS=10

# Web server username and group name
LUSER="lighttpd"
LGROUP="lighttpd"

# Okay, let us start cleaning as per $DAYS
/usr/bin/find ${CROOT} -type f -mtime +${DAYS} | xargs -r /bin/rm

# Failsafe
# if directory deleted by some other script just get it back
if [ ! -d $CROOT ]
then
        /bin/mkdir -p $CROOT
        /bin/chown ${LUSER}:${LGROUP} ${CROOT}
fi
Save and close the file. Set the permissions:
# chmod +x /etc/cron.daily/clean.cache

How do I backup installed cron jobs entries?
Simply type the following command to backup your cronjobs to a nas server mounted at /nas01/backup/cron/users.root.bakup directory:
# crontab -l > /nas01/backup/cron/users.root.bakup
# crontab -u userName -l > /nas01/backup/cron/users.userName.bakup

 = = = = = = = = = = = = = = = = = = = =
Q) 
crontab -e
$ */5 * * * * root /root/restart.sh  >/dev/null 2>&1

#!/bin/bash
# Process Monitor
# Send e-mail alerts when service goes down
# -------------------------------------------------------------------------
# Author: Anup Dixit
# -------------------------------------------------------------------------
SUBJECT="Backup Exec Agent Failure"
EMAIL="myemail@email.to"
EMAILMESSAGE="/tmp/emailalert.txt"
#path to pgrep command
PGREP="/usr/bin/pgrep"

# Daemon name,
DAEMON="httpd"

# find daemon pid
$PGREP ${DAEMON}

if [ $? -ne 0 ] # if daemon not running
then
# Generate email message body
echo "This is servername at location. The Backup Exec service is no longer running." > $EMAILMESSAGE
# send email alert
/usr/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
fi
= = = = = = = = = = = = = = = = = = = = = =