The cron on Linux Explained with Examples

The cron is a utility that allows you to run commands and scripts automatically at a specific interval. It accepts commands and time intervals as arguments. It schedules the specified commands to execute at the provided time intervals. This tutorial explains this process through various examples.

cron V/s anacron

The cron and anacron are separate packages but work together to execute scheduled tasks. The cron executes tasks at the scheduled time when the system is up. If the system is down, the task will not run. The anacron solves this issue. It checks all scheduled jobs at boot time and compares their scheduled times with the system downtime to identify the skipped jobs. If there is any skipped job, it runs that. It works only with daily, weekly, and monthly jobs.

The run-parts command

The cron and anacron execute the scheduled tasks using the /usr/bin/run-parts command. The run-parts command accepts a directory path as an argument. It executes all scripts, programs, and commands within the given directory in alphabetic order. This feature allows you to run scripts in a pre-defined order. You can prefix the script name with a numeral to arrange scripts in the required order. For example, you have three scripts: log.sh, user.sh, and backup.sh. You want to run these in the following order.

user.sh
log.sh
backup.sh
You can rename the above scripts as follows:
0_user.sh
1_log.sh
2_backup.sh

The /etc/crontab file

It is the main configuration file of cron. Before anacron, cron used it to execute the run-parts command on directories containing daily, weekly, and monthly cron jobs. Later, Linux moved this functionality to anacron. Now, this file contains only environmental variables and a commented crontab syntax that you can use to add entries to this file. Environmental variables let you customize the way you want to execute the jobs. By default, it defines the SHELL, PATH, HOME, and MAILTO variables.

SHELL Define the shell it uses to run the scheduled jobs.
PATH Specify a list of directories where it looks for the commands and scripts to execute the scheduled tasks.
MAILTO Specify a user account to whom it sends the result of tasks.

etc crontab file

Only the root account can edit this file. Although you can add crontab entries to this file, you should not do so. It is part of the cron package. A further update may overwrite your custom settings. Cron provides many locations (explained further) where you can add custom crontab entries.

The /etc/anacrontab file

It is the main configuration file of anacron. It contains the configuration that executes the run-parts command on directories containing daily, weekly, and monthly cron jobs. It adds a random delay between scheduled tasks to prevent the system from becoming over-exhausted during operations.

etc anacrontab

Similar to the /etc/cron file, only the root account can edit this file. This file has only one objective: running the run-parts command on the /etc/cron.[daily, weekly, monthly] directories. The default file has the necessary configuration for this. Do not use this file to schedule custom jobs. Since it is also a default configuration, any further updates can overwrite your custom configuration. Instead of this file, use the /etc/cron.[daily, weekly, monthly] directories for custom scripts.

The /etc/cron.d/ directory

This directory saves system-wide custom cron job files. Only the root user account can place cron job files in this directory. Usually, administrators place system management-related cron jobs (such as backing up data files, removing junk files, and creating logs) in this directory.

etc cron-d directory

The /etc/cron.[daily, weekly, monthly] directories

These directories organize time-specific cron jobs. Only the root user can update and manage these directories. The /etc/cron.daily directory specifies daily jobs. The /etc/cron.weekly directory provides weekly jobs. The /etc/cron.monthly directory contains the monthly jobs. The /etc/anacron file schedules the run-parts command to check these directories.

cron daily weekly monthly directory

The /var/spool/cron directory

This directory saves user-specific cron job files. The cron package includes the crontab command. The crontab command allows users to create and manage their cron files. The crontab creates a cron job file for each user account on the first use. It uses this file to save all cron jobs for that user account. A cron job is a task the user wants to run at a specific time interval. It places this file in the /var/spool/cron/ directory.

crontab command

Managing the crond daemon

The systemctl command manages all daemons. It supports many options and arguments. The following table lists the essential options to manage the crond daemon.

Command Description
#systemctl status crond Show the current status of the crond daemon.
#systemctl start crond Start the crond daemon in the current session.
#systemctl start crond Stop the crond daemon in the current session.
#systemctl enable crond Enable and start the crond daemon at boot time.
#systemctl disable crond Disable and start the crond daemon at boot time.

The crond daemon must be running to use the cron utility.

systemctl staus crond

The cron job execution process

  • The crond daemon executes cron jobs. A daemon is a process that continuously runs on the server and checks for particular actions to take. The crond daemon checks the crontab files of all users every minute. If it finds a task in any crontab file scheduled for that particular time, it executes that.
  • It first checks the /etc/crontab file for system-wide cron tasks. If the file contains any cron job, it executes that. The default file has no entry.
  • After the /etc/crontab file, it checks the /etc/cron.d/ directory. It uses the run-parts command to execute all scripts and commands alphabetically within this directory. By default, this directory has only one script named 0hourly.
    • The 0hourly file contains a default cron job that executes the run-parts command on the /etc/cron.hourly directly.
    • The /etc/cron.hourly/ directory contains a default script named 0anacron.
    • The 0anacron script runs the /usr/sbin/anacron -s command that executes the /etc/anacrontab file.
    • The /etc/anacrontab file executes the run-parts command on the /etc/cron.daily/, /etc/cron.weekly/, /etc/cron.monthly/ directories. If it finds a job in any of these directories, it checks its status. If the job has already been executed at its scheduled time, it checks the next job in the queue. If not, it executes the job.
  • After executing all scripts of the /etc/cron.d/ directory, it checks and executes user-specific cron jobs within the /var/spool/cron/ directory.

cron execution process

The crontab command

The crontab command allows you to create, edit, manage, and remove cron jobs. It uses the following syntax.

$crontab [option]

A root user can manage cron jobs for other user accounts. It uses the following syntax for it.

#crontab -u [username] [option]

It supports many options. The following are essentials.

-u Define the user account to manage (only the root user can manage cron jobs for other user accounts). Regular user accounts are not allowed to use this option.
-e Edit cron jobs (Also create a cron file for the user in the /var/spool/cron directory if it does not exist)
-l List user's cron jobs
-r Delete the user's cron file
-i Prompt before deleting
-T Test the corntab file syntax

crontab option

The crontab Entries

A crontab entry has six fields. The first five fields specify the time interval for the task you want to perform. The sixth field defines the task itself. The following table describes the time fields.

FieldValue it specify
FirstMinutes (0-59)
SecondHour (0-23)
ThirdDay of the month (0-31)
FourthMonth of year (1-12 or Jan-Dec)
FifthDay of the week (0–6, or Sun-Sat)
Key points:-
  • Any column with an asterisk (*) means all values are valid. It runs the job on all values of the field. For example, an asterisk in the minute field states that the job will execute every minute. Similarly, an asterisk in the month field states that the job will run every month.
  • A specific value in a field runs the job only when the value becomes true. For example, a value of 06 in the hour field runs the job only at the sixth hour of the day.
  • A range in a field runs the job on all range values. For example, if you specify the range 2-5 in the hour field, the job will run at 2:00 AM, 3:00 AM, 4:00 AM, and 5:00 AM.
  • You can also specify multiple specific values in a field, separating them by a comma. For example, if you use the value 2,5,7 in the hour field, the job will run at 2:00 AM, 5:00 AM, and 7:00 AM.
  • You can also use the division operator to specify more customized times. For example, a value */2 runs the job every even minute of the hour.
  • You can also use the standard three-letter abbreviations for months, days in the month, and days of the week columns, for example, mon for Monday and jul for July, respectively.
  • The day of the week starts with Sunday at 0 and goes through to Saturday at 6.

The crontab time format examples

The following table provides examples of the time field.

30 6 1 * *06:30 AM on the first day of every month
15 2 1 * 102:15 AM on the first day of the month and every Monday
*/2 2 1 * *On every even minute between 2:00 AM and 3:00 AM on the first day of every month
* */4 * * *On every fourth hour
30 6 * 1 1At 06:30 AM on every Monday of January
* * 1,5 * *On the first and fifteenth days of every month
* * * * 1,3,5On every Monday, Wednesday, and Friday
* * * * *Every Minute
*/15 * * * *Every 15 Minutes
30 * * * *Every 30 Minutes
0 0 * * *Everyday midnight
0 0 1 * *First day of month
0 0 15 * *15th of every month
0 0 * * 0Every Sunday midnight
0 12 * * 6,0At 12 PM on every Saturday and Sunday
0 9-17 * * 1-5Every Hour from 9 AM to 5 PM on Monday to Friday

The crontab entries examples

  • Login from the root user account and create two user accounts: user1 and user2.
  • List the /var/spool/cron/ directory.
  • Verify it contains no cron files for the created user accounts.
  • Switch to user1 and use the crontab -l command to list the current cron tasks.
#useradd user1
#useradd user2
#ls /var/spool/cron
#su user1
$crontab -l

useradd command

  • Change the current directory to the user's home directory.
  • List the home directory contents.
  • Create a script that makes a directory every time it runs.
  • Use the current minute as the directory name.
  • Make the script executable.
  • Set a cron job to execute the script file every minute.
  • List the corn job and verify the cron job.
$cd
$cat > user1.sh
mkdir $(date + "%M")
CTRL+D
$chmod +x user1.sh
$crontab -e
* * * * * /home/user1/user1.sh
:wq
$crontab -l
$ls
$date
note down the current minute and wait for another minute
$date
$ls
verify it contains a directory using the previous minute as the name

cronjob example

  • Exit from user1.
  • List cron jobs and verify the user1's cron file.
  • Open the user1's cron and update it to run the cron job every even minute.
  • Verify the update.
  • Remove the user1's cron file.
$exit
#ls /var/spool/cron
#cat /var/spool/cron/user1
#crontab -u user1 -e
 */2 * * * * /home/user1/user1.sh
:wq
#ls /home/user1
#date
Note down the current minute. Recheck after two minutes.
#ls
Verify the update
#crontab -r -u user1

updating cron file

Securing cron

By default, cron allows all users to set and use cron jobs. You can use the following files to allow or deny certain user accounts.

/etc/cron.allow Allow only the listed users. All remaining users are blocked.
/etc/cron.deny Deny only the listed users. All remaining users are allowed.

By default, neither file is present. You must create the file you want.

cron files

Allowing specific users

  • Create the /etc/cron.allow file and add user1.
  • Switch the user account to user1.
  • Add a cron job.
  • Verify the user can use the cron.
  • Exit user1 and switch the user account to user2.
  • Add a cron job.
  • Verify the user cannot use the cron utility.

allowing specific users to run cron

  • Exit user1.
  • Remove the /etc/cron.allow file.
  • Create the /etc/cron.deny file and add user1.
  • Switch the user account to user1 and add a cron job.
  • Verify that user1 can not use the cron utility.
  • Exit user1 and switch user account to user2.
  • Add a cron job.
  • Verify the user can use the cron utility.

denying specific users

Conclusion

The cron utility allows users to execute scripts and commands automatically at the scheduled time. This tutorial explained its configuration files and steps to schedule and verify corn jobs.

ComputerNetworkingNotes Linux Tutorials The cron on Linux Explained with Examples

We do not accept any kind of Guest Post. Except Guest post submission, for any other query (such as adverting opportunity, product advertisement, feedback, suggestion, error reporting and technical issue) or simply just say to hello mail us ComputerNetworkingNotes@gmail.com