Site icon Aditya Mittal Inc.

How to use Cron | Crontab in Linux | Ubuntu Server

How to use Cron | Crontab in Linux | Ubuntu Server

What is Cron Job?

Cron jobs allow a user to run specific command or a script at a scheduled time and day. You can also use this tool to execute the scripts periodically. It is one of the most commonly used tool on a Linux machine and you will need to utilize this tool sooner or later.

This tool is mostly utilized by sys-admins to perform daily or monthly backups or cleaning temporary directories (/tmp/directory). This service runs in the background and constantly checks /etc/crontab file.

How to install and create a new Cron Job?

In order to create or edit a CRONTAB file, use the following command:

# crontab -e

NOTE:
You don’t need to restart your server after creating a Cron Job.

Understanding the Format | Fields of a Crontab

Linux cron job is written as follows:

<Minute> <hour> <Day of the Month> <Month> <Day of the Week> <Command>

For Example:

30 08 10 06 * /home/amittal/full-backup.sh

So, the above-mentioned cron job will execute a shell script name full-backup which is located in /home/amittal/ directory on 10th June at 08:30 AM.

Cron Jobs use 24 hour time format.

FIELDALLOWED VALUE
Minute0 to 59
Hour0 to 23
Day of the Month1 – 31
Month1 – 12
Day of the Week0 – 6
CommandAny type of command to be
executed

Any of these fields can be set to an asterisk (*), which means ‘first through last’. So, if you want to run a job every day at 04:00 AM, you can write it as follows:

00 04 * * * command

Other options available in Cron Job

There are certain options available in a cron job which can be understood by search ‘man’ pages also known as manual pages. You can run following command to learn about those options:

# man crontab

Most widely used options are:

SyntaxDescription
– uSpecifies a user in the cron job
– lDisplays the current crontab that are already created
– rRemove the current crontab
– eEdit the current crontab

Few Examples

Here are a few examples which will help you to execute your cron jobs more efficiently. Once you have understood the basics, you can try complex cron jobs.

  1. Open the crontab editor
# crontab -e
  1. Remove your crontab and un-schedule all the crontab jobs
# crontab -r
  1. Display the list of cron jobs created by the user amittal.
# crontab -l -u amittal
  1. Run a backup script every week from Tuesday (2) – Saturday (6) at 07:30 AM.
30 07 * * 2-6 /home/amittal/backup.sh
  1. Run a backup script every year on 1st of January at 12:00 AM mid-night.
0 0 1 1 * /home/amittal/backup.sh
Exit mobile version