DEV Community

Cover image for What is a Cronjob and understanding syntax
Aasik
Aasik

Posted on

What is a Cronjob and understanding syntax

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.

  1. Hour - hour the command will run, ranging from 0-23 in a 24-hour notation

  2. Day of the month - date of the month the user wants the command to run, ranging from 1-31.

  3. Month - month the user wants the command to run. It ranges from 1-12, representing January until December.

  4. 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 
Enter fullscreen mode Exit fullscreen mode

To specify multiple values in a fields

  1. asterisk (*) -> Specifies all possible values for a field.

  2. comma (,) -> specifies a list of values

  3. dash(-) -> specifies a range of values

  4. Seperator(/) -> divides a value. If you want to run a script every twelve hours, write */12 in the Hour field.

  5. 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 
Enter fullscreen mode Exit fullscreen mode

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)