sajad torkamani

What is Cron?

Cron is a Unix program that helps you schedule tasks to be executed periodically (e.g., every hour or every 15 minutes). It's very useful for performing system administration tasks like backing up databases or cleaning up the hard drive.

Jobs scheduled by Cron are known as Cron jobs. These jobs are managed in a special file known as a crontab. Each user on a Unix system can have their own crontab to manage user-specific jobs.

Crontabs usually live under /var/spool/cron/crontabs. So if we have a user named john, then john's cron tasks will reside in /var/spool/cron/crontabs/john.

Cron task syntax

Cron task are scheduled using a special syntax that consists of two parts:

  • Schedule: controls when the task should run (e.g. hourly or daily)
  • Command: the actual command to perform the task; this can be any command you can run from the command line such as mysqldump.

The schedule part forms all the values before <command> as seen below:

<minute> <hour> <day_of_month> <month> <day_of_week> <command>
FieldAllowed values
minute0-59
hour0-23
day_of_month1-31
month1-12 or JAN-DEC
day_of_week0-6 or SUN-SAT

First cron task

Install postfix

Cron sends the cron tasks' output (stdout or stderr) via local mail. You need an MTA (Mail Transfer Agent) to configure the local mail. postfix is a popular MTA that does the job:

sudo apt install postfix

During the installation process, you'll be asked what default configuration you want to use. Select the local only option.

Add cron task

Open up your cron tab:

crontab -e

Add the following cron task:

 */1 * * * * echo "Hello, the time is: $(date --iso-8601=seconds)"

Save and exit crontab.

View cron output

Make sure the cron daemon is running:

sudo systemctl status cron

If it's shown to be Inactive, then run:

sudo systemctl start cron

Now, you can tail the /var/mail/<your_username> file to view the output of your cron task:

tail -f /var/mail/<your_username>

You should see something like:

Hello, the time is: 2021-04-19T15:00:01+01:00

More examples of cron tasks

The following task will make a curl request to http://google.com every Tuesday at 5.30 PM. You can use the Crontab Guru tool to validate and understand different cron expressions.

30 17 * * 2 curl http://www.google.com

Here are some more examples:

# Every Tuesday, Wednesday, and Thursday at 4:00 AM
0 4 * * 2-4 

# Every day at 4:00 AM
0 4 * * *

# Every 15 minutes
*/15 * * * * 

Closing thoughts

Cron jobs provide us a simple but powerful way of automating common administrative tasks. It is an invaluable tool to have for any system administrator!

Tagged: Unix