Cron Jobs in a nutshell

Abhijeet KumarAbhijeet Kumar
2 min read

Table of contents

“Cron jobs” if you don’t already know are an amazing way for scheduling tasks on Linux servers.

Cron is comprised of two parts i.e, “crontab” ( which contains your cron expressions ) and “crond” ( cron daemon which runs in the background & monitors crontab ).

Crontab can be edited using the command “crontab -e” and pointed to either a specific command or a shell script. Just make sure to use the absolute path for either of them.

Crond on the other hand executes the commands at a specific time.

Working together in harmony, they make sure the assigned task is executed at the right time.

Since we got the basic idea, let’s move on to the execution part.

A crontab contains seven fields as follows:-

1 2 3 4 5 6 7

Where,

1ST PLACE is for minutes (0–59)

2ND PLACE is for hour (0–24)

3RD PLACE is for day of month (1–31)

4TH PLACE is for month (1–12)

5TH PLACE is for day or week (0–7; both 0 & 7 can be used for sunday)

6TH PLACE is for user account (always make sure assigned user account has sufficient permissions to run the commands)

7TH PLACE is for the absolute path of command/shell script.

Here are some of the shortcuts to make jobs even more easier:-

@yearly @annually @monthly @weekly @daily @midnight @noon @reboot

These shortcuts do exactly what they say and they are worth implementing if the use case matches.

If you use shortcuts make sure to only include “user” and “command”.

Now that we are familiar with syntax let’s see some examples in action:-

1 2 3 4 5 root /usr/share/backup.sh

Which simply states

At 02:01AM on day-of-month 3 and on Friday in April “RUN” /usr/share/backup.sh as root

Let’s also see an example using the shortcut:-

@daily root /usr/share/backup.sh

Which simply means

“RUN” /usr/share/backup.sh as root on daily basis.

Also since we are using Linux, wildcards (*) are allowed too. Let’s see their example as well:-

1 2 5 root /usr/share/backup.sh

Which simply says,

At 02:01AM on friday in every month “RUN” /usr/share/backup.sh as root

[ NOTE:- “cron” requires the system to run 24/7 so it’s not ideal for running on a desktop/laptop. For this particular purpose use “anacron”. ]

On an ending note, I would also like to mention “crontab.guru” which is one of the best websites when it comes to creating/editing cron jobs. Give it a shot if you are new to server administration or want to check your expressions.

0
Subscribe to my newsletter

Read articles from Abhijeet Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abhijeet Kumar
Abhijeet Kumar