Menu

How to Run Cron Job in Linux.

0 Comments

One thing that’s always handy to know are cron jobs on Linux.  The cron is the most simple way to setup a task that needs to repeat.  In most distributions you’ll find your cron files located in the following directories:

/etc/cron.d
/etc/cron.daily
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly

Go ahead and create a file “/etc/cron.d/update” using your favorite text editor.

1. Run a cron every 2 Minutes

The first field is for Minutes. If you specify * in this field, it runs every minute. If you specify */2 in the 1st field, it runs every 2 minutes as shown below.

*/2 * * * * /home/newman/update.sh

Note: In the same way, use */5 for every 5 minutes, */15 for every 15 minutes, */30 for every 30 minutes, etc.

2. Run a cron every 2 Hours

The second field is for hours. If you specify * in this field, it runs every hour. If you specify */2 in the 2nd field, it runs every 2 hours as shown below.

0 */2 * * * /home/newman/update.sh

Note: In the same way, use */4 for every 4 hours, */5 for every 5 hours, */12 for every 12 hours, etc.

3. Run cron every Monday.

There are two simple ways to run a cron every Monday.  Think about your day of the week as one of the numbers below:

  • 0=Sun
  • 1=Mon
  • 2=Tue
  • 3=Wed
  • 4=Thu
  • 5=Fri
  • 6=Sat

This example runs the update.sh every Monday at midnight.

0 0 * * 1 /home/newman/update.sh
(or)
0 0 * * Mon /home/newman/update.sh

Note: Get into the habit of using numbers instead of the text equivalent. Remember that the week starts on Sunday so Sun = 0 and Mon = 1.

4. Run cron every 4 months (quarterly).

There is no direct way of saying ‘every 4 months’, instead you have to specify what specific months you want to run the job. Probably you may want to run the job on 5th month (May), and 10th month (Oct).

The fourth field is for Months. If you specify * in this field, it runs every month. To run for the specific month, you have to specify the number that corresponds to the month. For example, to run the job on May and Oct, you should specify 5,10 (or) you can simply use the 3 letter acronym of the month and specify May,Oct.

The third field is for DOM (Day of the Month). If you specify * in this field, it runs every day of the month. If you specify 1 in this month, it runs 1st of the month.

The following example runs the backup.sh twice a year. i.e 1st May at midnight, and 1st Oct at midnight.

0 0 1 5,10 * /home/newman/update.sh
(or)
0 0 1 May,Oct * /home/newman/update.sh

Note: Don’t make the mistake of specifying 5-10 in the 4th field, which means from 5th month until 10th month. If you want only 5th and 10th month, you should use comma.

Tags: ,