The Cron software utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. Once can schedule scripts to be executed periodically. It is usually used for system admin jobs such as backups or cleaning/tmp/ directories and more.
The following steps to be followed to set up a cron job in Ubuntu:
- Connect to server and update the system:
Before begin with setting up crontab connect the server and update the system software to the latest version available. We can do this by using below command:
#apt-get update && #apt-get upgrade
- Check if cron package is installed:
To check if cron is installed, run the following command –
#dpkg -l cron
- If cron is not installed, install the cron package on Ubuntu:
One can Install the cron package with package Manager using the following command-
#apt-get install cron
- Verify if cron service is running:
To check whether the cron service is running on the system, we can use the following command-
#systemctl status cron
- Configure cron job on ubuntu:
In order to set up cron jobs, one needs to modify the
/etc/crontabfile which can be done by only root user. You can edit the crontab file with following text editor.
Before we take example of cron tab execution let’s understand the common syntax of cron tab:
* * * * * /path/to/command arg1 arg2 OR * * * * * /root/backup.sh
In the syntax first * stand for representing minutes [0-59]. Second * stands for representing hour[0-23]. Third * stand for representing day [0-31]. Fourth star stands for representing month[0-12]. Fifth * stand for representing day of the week[0-7].
After all step for installation of cron tab and understanding common syntax, let’s execute a cron tab with suitable example.
Example #1: If we want to schedule a backup on first day of each month at
9 PM, the following command performs this operation.
#crontab -e //install your cron job by running this command. // Append the following entry. 0 9 1 * * /path/to/script/backup-script.sh
Example #2: Set up and run php script as cron job to run script every day at
#crontab -e //add cron job // Append the following entry. 0 10 * * * /path/to/myphpscript.php
Following options are available in crontab:
crontab -l : List the all your cron jobs.
crontab -r : Delete the current cron jobs.
For more information about cron, one can check the manual pages using:
man cron man crontab