A concise overview of Cron jobs

What is Cron?

Cron is a Unix program that lets you schedule and run jobs in the background at specific times or intervals. It is typically used to perform maintenance tasks such as backing up databases or generating daily reports.

Jobs scheduled by Cron are known as Cron jobs. These Cron jobs are managed in a special file known as a crontab. Each user profile on a Unix system can have their own crontab where they can schedule their own jobs.

Crontabs usually live under /var/spool/cron/crontabs. So if we have a user named ‘john’, then john’s cron jobs will live in /var/spool/cron/crontabs/john.

How to schedule a Cron job

Cron jobs are written using a special cron expression which consists of two parts:

Use crontab -e to open up your user’s cron jobs. You can schedule a cron job using the following syntax:

<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

Let’s look at some examples to see how these fields can be used to set up any schedule.

Example Cron jobs

The following job 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:

Emailing the results of Cron jobs

It’s common to email the results of Cron jobs to make sure our jobs are running successfully. One quick and easy way to set up email is to use something like Sendmail.

# Install sendmail
sudo apt-get install sendmail

# Configure sendmail
sudo sendmailconfig

# Send test email (will probably end up in your spam folder with default configuration)
echo "My test email being sent from sendmail" | /usr/sbin/sendmail <your_email>

Conclusion

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!

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: sajadtorkamani1@gmail.com