A cron job is a task automated using cron, a scheduler tool on a Unix System like Linux. Common cron jobs include running scheduled backups, updating software, clearing the cache, and monitoring the disk space, deleting files periodically which are no longer required and running system maintenance tasks etc.
Creating cron jobs helps reducing human error and save time as you don't need to repeatedly perform the same tasks.
Cronjob Syntax
The cronjob syntax consists of five fields with the following possible values:
1.Minute - minute of the hour the command will run, ranging from 0-59.
Hour - hour the command will run, ranging from 0-23 in a 24-hour notation
Day of the month - date of the month the user wants the command to run, ranging from 1-31.
Month - month the user wants the command to run. It ranges from 1-12, representing January until December.
Day of the week - day of the week for a command to run, ranging from 1-7.
If you want the cron daemon to run the root/backup.sh script every Saturday at 8.27 pm, here's what the cron command should look like:
27 20 6 root/backups.sh
To specify multiple values in a fields
asterisk (*) -> Specifies all possible values for a field.
comma (,) -> specifies a list of values
dash(-) -> specifies a range of values
Seperator(/) -> divides a value. If you want to run a script every twelve hours, write */12 in the Hour field.
Last(L) -> Users can use this operator in the day-of-the month and day-of-week fields. Writing 3L in the day-of-week field means the last Wednesday of the month.
Cron is commonly pre-installed by default in all Linux distributions. Otherwise, run the below command to install cron
sudo apt install cron
There are two configuration files you need to consider regarding cronjob, system crontab and user crontab. System crontab is used to schedule system-wide essential jobs that are only editable by those with root privileges. Meanwhile, we can use user crontab to create and edit jobs that only apply at the user level.
To create a crontab file
crontab -e
To display a list of active scheduled tasks
crontab -l
If the system has multiple users, you can view their crontab files by entering the command below as a superuser
crontab -u username -l
To delete scheduled tasks
crontab -r
crontab -i is similar to crontab -r, except you will get a confirmation before deleting the tasks.
To run a cron job, connect to your Linux system using terminal with root permissions. Then create a crontab file and add the script using text editors like vim or Nano.
Top comments (0)