Setup crontab file

In Linux, Cron is a daemon/service that executes shell commands periodically on a given schedule. Cron is driven by a crontab, a configuration file that holds details of what commands are to be run along with a timetable of when to run them.

CREATING A CRONTAB FILE

Create a crontab file by:

crontab -e

The above command will open a terminal editor with a new blank crontab file, or it will open an existing crontab if you already have one. You can now enter the commands to be executed

List of active crontab entries by entering the following terminal command

crontab -l

However, you may already have a crontab file, if you do you can set it to be used with the following command

crontab -u 

example:

crontab -u long-dev ~/crontab

this command would set long-dev’s crontab file to that of the file named “crontab” residing in long-dev’s home directory.

CRONTAB SYNTAX

A crontab file has six fields for specifying minute, hour, the day of a month, month, the day of a week and the command to be run at that interval

*     *     *     *     *  command to be executed
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- day of week (0 - 6) (Sunday=0)
|     |     |     +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

EXAMPLES

* * * * *  #Runs every minute
30 * * * *  #Runs at 30 minutes past the hour
45 6 * * *  #Runs at 6:45 am every day
45 18 * * *  #Runs at 6:45 pm every day
00 1 * * 0  #Runs at 1:00 am every Sunday
00 1 * * 7  #Runs at 1:00 am every Sunday
00 1 * * Sun  #Runs at 1:00 am every Sunday
30 8 1 * *  #Runs at 8:30 am on the first day of every month
00 0-23/2 02 07 *  #Runs every other hour on the 2nd of July

As well as the above there are also special strings that can be used:

@reboot  #Runs at boot
@yearly  #Runs once a year [0 0 1 1 *]
@annually  #Runs once a year [0 0 1 1 *]
@monthly  #Runs once a month [0 0 1 * *]
@weekly  #Runs once a week [0 0 * * 0]
@daily  #Runs once a day [0 0 * * *]
@midnight  #Runs once a day [0 0 * * *]
@hourly  #Runs once an hour [0 * * * *]

MULTIPLE COMMANDS

A double-ampersand “&&" be used to run multiple commands consecutively. The following example would run command_01 and then command_02 once a day:

@daily command_01 && command_02

DISABLING EMAIL NOTIFICATIONS

By default, a cronjob will send an email to the user account executing the cronjob. If this is not needed put the following command at the end of the cronjob line

>/dev/null 2>&1

Or, you can disable all email notifications by adding the following to the top of the crontab file

MAILTO=""

REMOVING A CRONTAB FILE

To remove your crontab file simply enter the following terminal command:

crontab -r

Leave a Reply

Your email address will not be published. Required fields are marked *