How to Write a Cron Job: Syntax and Examples

Colorful HTML code displayed on a computer screen for programming projects.

What Is a Cron Job?

A cron job is a scheduled task that runs automatically at specified intervals on a Unix or Linux system. The name comes from Chronos, the Greek god of time. Cron is managed by the cron daemon (crond), a background process that reads a configuration file called the crontab and executes the listed commands on their defined schedule.

Cron is the backbone of automation for developers, system administrators, and DevOps engineers. Scheduled database backups, log rotation, report generation, cache warming, health checks, API polling — all of these and more are commonly implemented as cron jobs. Understanding cron syntax is a foundational DevOps skill that you will use throughout your career.

The Crontab File

Each user on a Linux system can have their own crontab. To edit your crontab, run:

  • crontab -e — Open your crontab in the default editor
  • crontab -l — List your current crontab entries
  • crontab -r — Remove your crontab entirely (use with caution)
  • sudo crontab -u www-data -e — Edit the crontab for the www-data user

System-wide cron jobs can also be placed in /etc/cron.d/, /etc/cron.daily/, /etc/cron.hourly/, /etc/cron.weekly/, and /etc/cron.monthly/ for coarser scheduling without writing cron syntax.

Cron Syntax Explained

Every crontab entry has six fields separated by spaces:

  • Field 1 — Minute: 0-59
  • Field 2 — Hour: 0-23
  • Field 3 — Day of month: 1-31
  • Field 4 — Month: 1-12 (or names: jan, feb, …)
  • Field 5 — Day of week: 0-7 (both 0 and 7 mean Sunday, or use names: sun, mon, …)
  • Field 6 — Command: The full shell command to execute

A helpful mnemonic: Minute, Hour, Day, Month, Weekday — “Monkeys Hate Doing Math Work.”

Special Characters in Cron

Cron expressions support several special characters that give you fine-grained control over scheduling:

  • * (asterisk): Matches every possible value for that field. * in the minute field means “every minute.”
  • , (comma): Specifies a list of values. 1,15,30 in the minute field runs at minutes 1, 15, and 30.
  • – (hyphen): Specifies a range. 9-17 in the hour field means every hour from 9 AM to 5 PM.
  • / (slash): Specifies a step. */15 in the minute field means every 15 minutes. 0-23/2 means every 2 hours.

Cron Examples with Explanations

Here are real-world cron job examples covering the most common scheduling patterns:

  • 0 * * * * /usr/bin/python3 /opt/scripts/hourly_report.py — Run a Python script at the top of every hour.
  • 30 2 * * * /usr/bin/mysqldump -u root mydb > /backups/mydb.sql — Back up a MySQL database every day at 2:30 AM.
  • */5 * * * * /usr/local/bin/check_service.sh — Run a health check script every 5 minutes.
  • 0 9 * * 1-5 /opt/scripts/send_daily_email.sh — Send an email at 9 AM every weekday (Monday through Friday).
  • 0 0 1 * * /opt/scripts/monthly_cleanup.sh — Run a cleanup script at midnight on the first day of every month.
  • 0 0 * * 0 /usr/bin/certbot renew — Attempt SSL certificate renewal every Sunday at midnight.
  • */10 9-18 * * 1-5 /opt/scripts/poll_api.sh — Poll an API every 10 minutes between 9 AM and 6 PM on weekdays.

Special Cron Strings

Many cron implementations support convenient special strings as shorthand for common schedules:

  • @reboot — Run once at system startup
  • @yearly or @annually — Run once a year (0 0 1 1 *)
  • @monthly — Run once a month (0 0 1 * *)
  • @weekly — Run once a week (0 0 * * 0)
  • @daily or @midnight — Run once a day (0 0 * * *)
  • @hourly — Run once an hour (0 * * * *)

Best Practices for Writing Cron Jobs

Cron jobs that work in development can silently fail in production if you are not careful. Follow these best practices to write reliable, maintainable scheduled tasks:

  • Use absolute paths everywhere: Cron runs with a minimal environment. Your PATH is not the same as in an interactive shell. Always use /usr/bin/python3 instead of just python3, and absolute paths for scripts and output files.
  • Redirect output: By default, cron emails output to the local mail spool, which most servers do not process. Redirect stdout and stderr explicitly: command >> /var/log/myjob.log 2>&1.
  • Test before scheduling: Run the exact command string manually as the user the cron job will run as before adding it to the crontab. Catch permission and path issues upfront.
  • Keep jobs idempotent: Design cron scripts so that running them twice has the same effect as running them once. This protects against duplicate runs during system restarts or time changes.
  • Add locking to prevent overlaps: If a cron job might run longer than its schedule interval, use a lock file or flock to prevent multiple instances from running simultaneously. flock -n /tmp/myjob.lock -c "/opt/scripts/myjob.sh" is a simple approach.
  • Set MAILTO to suppress or redirect email: Add MAILTO="" at the top of your crontab to suppress all output emails, or MAILTO="[email protected]" to route them to a real address.
  • Document your cron jobs: Add comments above each entry explaining what it does, why it runs at that time, and who owns it. Crontabs without comments become archaeology projects.

Troubleshooting Cron Jobs

When a cron job does not run as expected, these debugging steps resolve the vast majority of issues:

  • Check /var/log/syslog or /var/log/cron for cron execution logs: grep CRON /var/log/syslog.
  • Verify the cron daemon is running: systemctl status cron or systemctl status crond.
  • Test the exact command manually as the correct user, with the exact environment cron would use.
  • Check file permissions — the script must be executable (chmod +x script.sh) and readable by the cron user.
  • Confirm the cron syntax is correct using an online cron expression validator.

Cron Alternatives for Modern Infrastructure

While cron remains the default scheduling solution on Linux, modern infrastructure sometimes calls for alternatives: systemd timers offer better logging and dependency management; Kubernetes CronJobs handle scheduling in containerized environments; cloud-native schedulers like AWS EventBridge, Google Cloud Scheduler, and Azure Logic Apps provide managed scheduling without server management overhead. That said, for any task running on a traditional Linux server, cron remains the simplest and most reliable option.

Try our free developer utility tools — JSON formatter, Base64 encoder, regex tester, and more, all in one place.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top