Cron job

Cron is used to schedule jobs on a regular basis.
It has the following files and directory:

  • /etc/crontab – system crontab file. Root user use it to create automatic task.
  • /etc/cron.d – crontab extension directory,  contain cron files.
  • /etc/cron.daily: – this directory contain scripts, all scripts in the directory run once a day.
  • /etc/cron.hourly: – this directory contain scripts, all scripts in the directory run once in an hour.
  • /etc/cron.monthly:  – this directory contain scripts, all scripts in the directory run once in a month.
  • /etc/cron.weekly: – this directory contain scripts, all scripts in the directory run once in a week.

cron syntax:
<minute> <hour> <day of month> <month> <day of the week> <user account> <command to run>

For example:
* * * * * root ls /etc
will run “ls /etc” as a root user every minute.

0 6 * * 1-5  root ls /var
will run at 6Am from Monday to Friday (day start from 0=sunday).

We can also use shortcut:
@hourly  root ls /proc
will run every hour “ls /proc“, useful when we only want it to happen once a day and we don’t care exactly when.The other macros are @daily, @monthly, @yearly

 

if we want to see the cron jobs for our user:
crontab -l
if we are root user:
crontab -l -u
will show the cron job for <user>
if we want to edit, remove or add cron job to our user:
crontab -e
will open text editor for the crontab file for our user. When we edit crontab file, then we should skip the “user” column, we only need the command, and the specific   interval.

 

Nice trick that we can do to run cron in interval less than 1 minutes is to use the sleep command.The sleep command get as a parameter a number of second, and wait until this second pass.
So if we want to have command to run every 30 minutes:


* * * * * <command>
* * * * * sleep 30; <command>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s