cron tutorial

What is cron?

cron is a daemon available in UNIX based systems which runs in background and automatically executes scripts or commands  at the specified time mentioned by the user.

Example Scenarios where cron can be useful


  • Connecting to the Internet and downloading E-Mail
  • Cleaning up personal temporary directory
How to check whether cron is running or not

On  most of the Linux distributions, cron is already installed and is started by the startup scripts.

jamal@jamal-Lenovo-G580:~$ ps ax| grep "cron"
 1356 ?        Ss     0:00 cron
 3793 pts/0    S+     0:00 grep --color=auto cron

The top line shows that the cron is running and the bottom is the one we have searched

How to schedule a job in cron

There are different ways to achieve this:

1. User specific
2. System Level

System Level:

In the /etc, there are subdirectories called cron.hourly, cron.monthly, cron.weekly and cron.daily. Place your script in any of these directories depending on your time requirements. If you want your script to run hourly then place it in cron.hourly subdirectory

If you want more flexibility i.e. wants to execute your script at 9 pm on every Monday, you can use the /etc/crontab file




SHELL is the one under which cron runs. 
PATH contains the directories which the cron looks for the scripts or any programs

The next lines runs the daily, hourly, weekly and monthly cron jobs

User Level:

Each and every user can have its own  crontab file as all the apps are not available for each user. This is present in the following location : /var/spool/cron/crontabs/<user>

By default , cron file is not created for the user. We have to create it by using crontab -e on the command line.  When you invoke the command, it opens your default editor which is vi.

Creating a cron schedule:

Cron  requires you to use the following syntax:

min hr dom month dow  user cmd

The above is self explanatory. When you are using a user specific crontab , there is no need to mention the user. The syntax changes to 

min hr dom month dow  cmd

We will now see some of the examples for /etc/crontab

If you want your script/command to execute one min past every hour

01 * * * * root echo "Runs one minute past every hour"

If you want your script to execute every minute

*/1 * * * * root echo "Commands run every minute"


Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig