Scheduling Commands With Crontab In Ubuntu
The following applies to any linux distribution
Crontab
Crontab is an integral part of most Linux distributions.It is a simple text file that holds a list of commands that are scheduled to be run at specified times. These commands, and their relative run times, are controlled by the ‘cron’ daemon and are executed in the system background.
Each user on a Linux system has their own crontab which contains the schedule of commands. In order to edit or create a crontab, one must use the text editor that is specified by the system, ‘nano’ being the default on my system. To create a crontab open a terminal and type:
crontab -e
‘nano’ will open with a blank window for the job schedule to be entered. Each line represents a seperate cron job entry – also known as a ‘cron job’.
Creating a ‘cronjob’
Each section in a cronjob is separated by a space, with the final section having one or more spaces in it. No spaces are allowed within sections 1-5, only between them. Sections 1-5 are used to indicate when and how often the task has to be executed. This is how a cron job is layed out:
minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command
Example 1
01 04 1 1 1 /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand at 4:01am on any Monday which falls on January 1st. An asterisk (*) can be used so that every instance (every hour, every weekday, every month, etc.) of a time period is used. Code:
Example 2
01 04 * * * /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand at 4:01am on every day of every month.
The “/usr/bin/somedirectory/somecommand” text in the above examples indicate the task that will be run at the specified time. It is recommended to use the full path to the desired command as shown in the above examples. Crontab will echo any mistakes found in a cronjob. The crontab will start running as soon as it is properly edited and saved.
Other crontab options
crontab -l option causes the current crontab to be displayed on standard output.
crontab -r option causes the current crontab to be removed.
crontab -e option is used to edit the current crontab using the editor specified by the EDITOR environment variables ($EDITOR=vi crontab -e).
Note: The double-ampersand (&&) can also be used in the “command” section to run multiple commands consecutively.









