DevOps Blog

A Beginner’s Guide to Cron: Scheduling Tasks Like a Pro

What is Cron?

Cron is a time-based job scheduler in Unix-like operating systems. It runs tasks (called "cron jobs") automatically at specified intervals—whether daily, weekly, or even every minute.

Common uses include:

  • Running backups
  • Clearing temporary files
  • Sending scheduled emails
  • Automating system maintenance

Understanding the Cron Syntax

Cron jobs are defined in a crontab (cron table) file. Each line represents a job and follows this structure:

* * * * * command-to-execute └── Day of the week (0 - 7, where 0 and 7 = Sunday) └──── Month (1 - 12) └────── Day of the month (1 - 31) └──────── Hour (0 - 23) └────────── Minute (0 - 59)

Special Characters

  • * = Any value (e.g., every minute, every hour)
  • , = List multiple values (e.g., 1,15,30)
  • - = Range (e.g., 1-5 for Monday to Friday)
  • / = Step values (e.g., */5 for every 5 minutes)

How to Edit Your Crontab

To create or modify cron jobs, use:

crontab -e # Opens your user's crontab in the default editor

To list your scheduled jobs:

crontab -l

To remove all cron jobs:

crontab -r

(Be careful—this deletes everything!)


Practical Cron Examples

1. Run a Script Every Day at 3 AM

0 3 * * * /path/to/script.sh

2. Run a Command Every 5 Minutes

*/5 * * * * /usr/bin/php /var/www/cleanup.php

3. Run a Backup Every Sunday at Midnight

0 0 * * 0 /usr/bin/rsync -a /home/user/backup/ /mnt/backup/

4. Schedule a Python Script on Weekdays at 5 PM

0 17 * * 1-5 /usr/bin/python3 /home/user/script.py

Common Pitfalls & Tips

  1. Use Absolute Paths – Cron runs with a limited environment, so always specify full paths to commands and files.
  2. Check Logs – Cron logs are usually found in /var/log/syslog or /var/log/cron.
  3. Test First – Run your script manually before scheduling to ensure it works.
  4. Redirect Output – To debug or log output, use >> or 2>&1:
    * * * * * /path/to/script.sh >> /var/log/cron.log 2>&1

Conclusion

Cron is an essential tool for automating tasks on Unix-like systems. With just a few commands, you can schedule jobs to run at precise times, saving you time and effort.

Now that you know the basics, try setting up your first cron job!

Got questions? Drop them in the comments below!


Happy scheduling!