Cron Jobs

Cron allows Linux and Unix users to run commands or scripts at a given date and time. We can schedule scripts to be executed periodically. Cron is one of the most useful tool in a Linux or UNIX like operating systems. It is usually used for sysadmin jobs such as backups or cleaning /tmp/ directories and more. The cron service runs in the background and constantly checks the /etc/crontab file, and /etc/cron.*/ directories. It also checks the /var/spool/cron/ directory.

Types of cron configuration files –

  1. The UNIX / Linux system crontab – Usually, used by system services and critical jobs that requires root like privileges. The sixth field 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 or create your own 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

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

Cron is controlled by a set of files called “crontabs”. There is the master file in /etc/crontab. Each users cronjob is stored in /var/spool/cron/username directory. To see master file type the following cat command.

$ cat /etc/crontab