Sunday, December 2, 2012

How to set up cron job in linux

What is a cron job?

As a network admin, its very important that we know the use of the crontab command which is used to setup cron jobs.


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, /etc/cron.*/ directories. It also checks the /var/spool/cron/ directory
crontab is the command used to install, deinstall or list the tables (cron configuration file) used to drive the cron 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.
To edit your crontab file, type the following command at the UNIX / Linux shell prompt:$ crontab -e

Syntax of crontab (Field Description)

Your cron job looks as follows for user jobs:
 
1 2 3 4 5 /filepath ag1 ag2
 
OR
 
1 2 3 4 5 /root/runscript.tcl
 
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])
  • /filepath - Absolute path of the script or command name to schedule* * * * * command to be executed
Note: Only use absolute paths in the cron. Do not use relative paths.

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"



No comments:

Post a Comment