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
How to schedule a Cron job
Cron jobs are written using a special cron expression which 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
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>
|month||1-12 or JAN-DEC|
|day_of_week||0-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:
0 4 * * 2-4– Every Tuesday, Wednesday, and Thursday at 4:00 AM.
0 4 * * *– Every day at 4:00 AM.
*/15 * * * *– Every 15 minutes.
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>
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!