Let’s explore crontab, its commands, and various operations associated with Crontab.

We will learn how to schedule tasks using the cron utility, and in last, we will also discuss some of the online tools which help us with formatting and testing the cron commands.

Origin

Crontab stands for “cron table“. The word cron has been taken from the Greek word Chronos meaning time. Crontab is a system daemon process that will automatically perform some tasks and jobs as per the scheduled time.

Use cases

Crontab is useful to perform various operations such as handling automated backup, rotating log files, syncing files between remote machines and clearing out temporary folders, etc. Crontab can be used for any kind of work, but it becomes especially useful when we start dealing with system administration type of work.

Using cron, an administrator can schedule a job to run on a specific time and day.

So let’s see how we can set this up.

Crontab Syntax

To execute a list of commands, cron utility reads the configuration files. To interpret the lines in the crontab configuration tables, it follows a Crontab syntax. Crontab has six fields, and the first five(1-5) fields define the date and time of execution. The last field, i.e., 6th field, could be a username and/or task /job/command/script to be executed.

*    *    *    *    *    USER_NAME   COMMAND/SCRIPT-TO-EXECUTE

│   │   │   │    │
│   │   │   │    │
│   │   │   │     |_________   Day of Week (0 – 6) (0 is Sunday, or use names)
│   │   │    |____________ Month (1 – 12),* means every month
│   │    |______________  Day of Month (1 – 31),* means every day
│    |________________  Hour (0 – 23),* means every hour
|___________________ Minute (0 – 59), * means every minute

Notes:

  • Asterisk (*) is used for matching all possible values for a field.  For instance, an asterisk used in the hour field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.
  • username is optional(available only if it is the system crontab file)

Examples:

Let’s understand the above syntax with some examples

1. Schedule a cron to execute at 5 AM daily

0 5 * * * /scripts/job.sh

2. Schedule a cron to execute twice a day at 6 AM and 6 PM

0 6,18 * * * /scripts/job.sh

3. Schedule a cron to execute on every minute

* * * * * /scripts/job.sh

4. Schedule a cron to execute on every Monday at 7 PM.

0 19 * * mon /scripts/job.sh

5. Schedule a cron to execute every 15 minutes.

*/10 * * * * /scripts/job.sh

6. Schedule a cron to execute on selected months

* * * feb,jun,oct * /script/job.sh

7. Run the shell script /home/script/backup.sh on March 4 at 7:25 A.M

25 7 4 3 * /home/script/backup.sh

8. Schedule a cron to execute every 30 Seconds

Since we do not have control over seconds in the Crontab, but we can achieve it through the below two-step process.

  • Let’s first schedule a task that runs every minute.
* * * * * /home/scripts/script.sh
  • Now let’s use sleep command to pause the execution for 30 seconds.
* * * * * sleep 30; /home/scripts/script.sh

The above task will stop the execution for 30 seconds, and it will resume again.

Type of Cron configuration files

There are two types of Cron configuration files:

The UNIX/Linux System Crontab

This requires root privilege because usually it is used for system services and critical jobs. The sixth field (in the above syntax description) is the name of a user for the command to run as. It gives the ability to system crontab to run commands as any user.

The User Crontab

User can also install their own cron jobs using the crontab command. Here also, the sixth field(in the above syntax description) is the command to run, and all commands run as the user who created the crontab.

Each user can have their own crontab file, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. We need to use crontab command for editing or setting up our own cron jobs.

How does it work?

The cron service (daemon) runs in the background and constantly checks(every minute) the /etc/crontab file, and /etc/cron.*/ directories. It also checks the /var/spool/cron/ directory.

Commands are executed by cron when the minute, hour, and month fields match the current time, and at least one of the two-day fields (day of the month, or day of the week) match the current day.

Basic Commands

Listing out Existing Cron Jobs

We can list out all the Cron jobs without opening the crontab configuration file using below command

crontab -l

If there is no existing job it will return the output as

[geekflare@localhost ~]# crontab -l
no crontab for geekflare
[geekflare@localhost ~]#

If the user has already added some of the jobs it will display as follows.

[geekflare@localhost ~]# crontab -l
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
0 */1 * * * /home/account/scripts/updateAccountStatuses.sh
0 */1 * * * /home/account/scripts/reActivateAccountStatus.sh
[geekflare@localhost ~]#

Cron table is user-specific, which means,  you must be logged in with a specific user to see the cron table list.

List Cron for Particular user

To list scheduled jobs of another user, use option as -u (User) and -l (List).

crontab -u another_username -l

Example: crontab -u geekflare -l

Add/Modify Crontab Entries

To edit the crontab entry, we can use -e option as shown below.

crontab -e

The above command will open vi editors where you specify the details of the job and save the file. Once saved, you can verify if cron is configured or not with crontab -l.

Add/Modify Crontab Entries for Particular User

We can edit the crontab for another user using the below command

crontab -u another_username -e

Example: crontab -u geekflare -e

Remove Crontab Entry

Use <strong>-r</strong> parameter with Crontab to remove complete scheduled jobs without confirmation from crontab

crontab -r

If you want confirmation before deleting scheduled jobs, use <strong>-i</strong> option with -r, which will prompt confirmation from the user before deleting the user’s crontab.

crontab -i -r
[geekflare@localhost ~]# crontab -i -r
crontab: really delete geekflare's crontab?

Crontab Special String

Other than the above syntax we discussed, we can also use eight special strings provided by Crontab. It will not only save us time but will also improve readability.

Special StringDescription
@rebootRun once, after startup.
@yearlyRun once a year, i.e., 0 0 1 1 *
@annuallySame as @yearly
@monthlyRun once a month i.e., 0 0 1 * *
@weeklyRun once a week i.e., 0 0 * * 0
@dailyRun once a day i.e., 0 0 * * *
@midnightSame as @daily
@hourlyRun once an hour i.e., 0 * * * *

Crontab Special String Examples

1. Crontab to schedule tasks on a yearly basis

@yearly /scripts/greeting.sh

We can execute the above one for sending a new year greeting, It will execute at the first minute of every year.

2. Crontab to schedule tasks to execute on a monthly basis.

@monthly /scripts/cleanup.sh

We can execute the above one to perform some cleanup activities at the beginning of every month.

Similarly, we can use other Crontab special string for weekly, daily, and hourly purposes.

Cron Directory

The system administrator can use a system-wide cron schedule which comes under the predefine cron directory as shown below

  • /etc/cron.d
  • /etc/cron.daily
  • /etc/cron.hourly
  • /etc/cron.monthly
  • /etc/cron.weekly

Crontab Realtime Examples

Let’s discuss some of the real-time examples, that a system administrator or IT professionals usually use.

Delete empty files and directory

45 0 * * * geekflare find /tmp -type f -empty -delete

Above cron expression will find the empty files and directory from /tmp directory and it will delete them. This job will run at 12.45 AM on a daily basis. We need to mention the user name to perform this job. In the above example, geekflare user is performing cron job operation.

Execute multiple tasks using a single cron

* * * * * /home/scripts/backup.sh; /home/scripts/scritp.sh

Multiple tasks/jobs can be separated using a semicolon(;) and can be assigned to a single cron expression.

Cron formatting & testing tools

So far we discussed commands and syntax of crontab to schedule a task. But what if you are not a system administrator and your job is not to set up Cron regularly, it might not be possible to remember the syntax and it opens up the room for error. Don’t worry we have a solution to this problem.

There are several Cron formatting tools available online.

# 1. Cron Job Generator

Cron Job Generator is a very user-friendly GUI where you can specify the minute, days, and path of the script to generate crontab.

Let’s take a real-time example where I have to execute /home/processMonitor.sh at every 5 minutes between Monday to Friday.

So, I got the below Cron syntax which I can put in my crontab by executing

crontab –e
0,5,10,15,20,25,30,35,40,45,50,55 * * * 1-5 /home/processMonitor.sh

# 2. Crontab Generator

Crontab Generator is another handy tool to generate crontab and with this tool, you can also add if you want to save cron output to the file or send it to email.

# 3. Crontab Guru

Crontab Guru is a simple online cron schedule expression editor. In addition, it provides a useful means of monitoring your cronjob. All we need to do is copy a command provided and append at the end of the crontab definition. In case cron job fails or doesn’t even start, you will receive an alert email.

In the below example, Job will execute at 04:05, every day, every month and every week.

Conclusion

I hope the above helps you to get a better understanding of Crontab and setting up cron jobs. Scheduling jobs through Cron is one of the many tasks performed by Linux Admin.

More on Linux