The Complete Guide to Cron Expressions

For decades, the simple cron utility has been the backbone of server automation. Whether it's backing up databases, sending weekly newsletters, or cleaning up old logs, cron is everywhere.

Yet, despite its simplicity, writing a cron expression can feel like deciphering hieroglyphics. Let’s demystify the syntax once and for all.

The 5-Field Standard Syntax

A standard cron expression consists of five fields separated by spaces:

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of the month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
│ │ │ │ │
* * * * *

Common Special Characters

  • * (Asterisk): Matches all values. * in the hour field means "every hour".
  • , (Comma): Specifies a list of values. 1,15,30 in the minute field means run at minutes 1, 15, and 30.
  • - (Hyphen): Defines a range. 9-17 in the hour field means every hour from 9 AM to 5 PM.
  • / (Slash): Denotes increments. */15 in the minute field means "every 15 minutes".

3 Dangerous Cron Pitfalls to Avoid

1. The Day-of-Month vs. Day-of-Week Conflict

If you specify both a day of the month (e.g., 15) and a day of the week (e.g., 5 / Friday), cron runs the job when either condition is met.

  • Example: 0 0 15 * 5 runs on the 15th of the month AND every Friday.

2. Assuming a Default Timezone

Cron daemons run on the system's timezone (usually UTC on production servers, but local time on development laptops). A job scheduled for 0 2 * * * (2 AM) might run at 10 PM or 6 AM for your users if timezone differences aren't accounted for.

3. Overlapping Executions

If you schedule a job to run every minute (* * * * *), but the script takes 90 seconds to complete, a new instance will spawn before the first one finishes. This can lead to database locks, memory exhaustion, and data corruption.

Conclusion

Understanding cron expressions is essential for backend engineering. However, scheduling is only half the battle. Monitoring whether your cron expressions actually fire is just as critical. Keep your expressions clean, document their schedules, and always monitor their execution.