How to schedule tasks on Linux using crontab

Cron in Linux

Cron is a time-based job scheduler in Linux or Unix operation system. It is most suitable for scheduling repetitive tasks on regular intervals such as daily, weekly or monthly. The origin of the name cron is from the Greek word for time. 

Crontab in Linux

Crontab (CRON TABle) is a table where we can schedule the repeated tasks to run in background. It is a daemon that will automatically run the scheduled tasks on a regular interval. Crontab is very useful to run the routine tasks such as system scanning, daily backups etc.

Syntax of Crontab entries

Crontab has six fields. The 1-5 fields defines the date and time of execution and 6th field used for command or script to be executed.

  • MI= minute field. Allowed values are 00,01,02…59
  • HH= hour field. Allowed values are 00,01,02…23
  • DD=day of month. Allowed values are 01,02,03…31
  • MM=month of year. allowed values are 01,02,03…12
  • DW=day of week. Allowed values are 0,1,2…6 [0-Sunday,1-Monday…6-Saturday]

How to Add or Edit Crontab

You need to use -e option as below to make an entry in the crontab. It will open the crontab in the VI editor. You just need to insert an entry to schedule the tasks and save it using :wq command

To List crontab entries

You can list out all the existing crontab entries using -l option as below. If there is no entry in the crontab, this command will return the empty screen.

To remove crontab entries

The option -r is used to remove the crontab entries as below. It will remove complete scheduled jobs without confirmation from user.

Prompt before delete crontab entries

You need to use -i option with -r before deleting user’s crontab. It will ask the confirmation from user to delete the crontab entries.

Example 1: Schedule the tasks in Linux using crontab

We want to perform some housekeeping tasks such as deleting old log files and auditing on file permission in the system. We can use cron scheduler offered by Linux system. We can schedule it to run specific time, day, month, year and so on. Scheduler will read the crontab entries every minute and execute the scheduled programs whenever scheduling condition become true.

Here, we declared minute field as 00 and rest of the fields as *.’*’ means true for all allowed values. Above setting will run the log_clean.sh program located under /scripts folder for every hour that is 00:00, 01:00, 02:00,…23:00 of all days, all months and all week days. Further each field should be separated by single space. As no such script available, log file captured the error message below.

Output

Example 2 : Execute command using crontab

Lets write the date in the output.log file for every minutes using crontab. We have set the crontab entry as below to achieve this.

Output

The echo command executed every minutes and print the date in the output.log file as below

Recommended Articles

How to run the script in the background mode?