How to Write a Cron Expression

A cron expression is a short code that defines how often a task runs, using five fields. The syntax looks confusing at first, but the logic behind it is simple.

Summary

A cron expression is a short code that defines how often a task runs, using five fields. The syntax looks confusing at first, but the logic behind it is simple.

Step by step

  1. Memorize the field order: minute-hour-day of month-month-day of week. Mixing up the order is the most common mistake.
  2. Start with a simple example, like writing "every day at 9am."
  3. Test what you write in a validator and let the tool show you the next scheduled run times.
  4. Check whether the server's timezone matches what you expect. Cron generally runs on server time, and that's the detail people miss most often.

Why it matters

A wrong cron expression doesn't throw an error. If the syntax is valid, the system accepts it quietly and runs it when you wrote it, not when you meant it. A job that should run daily but runs every minute will strain the server. One that never runs can leave you without backups for weeks. Checking what you wrote is as much a part of the job as writing it.

Patterns you'll use often

  • Every day at midnight: 0 0 * * *
  • Every hour on the hour: 0 * * * *
  • Every 10 minutes: */10 * * * *
  • Weekdays at 8:30 a.m.: 30 8 * * 1-5
  • First day of every month at 6 a.m.: 0 6 1 * *
  • Every Sunday at 3 a.m.: 0 3 * * 0

Common mistakes

  • Leaving the minute field as an asterisk. Get the hour right but forget the minute, and the job runs every minute of that hour.
  • Scheduling for the 31st. In shorter months the job simply doesn't run. For month-end tasks, the 1st is safer.
  • Putting lots of jobs on the same minute. If everything starts at midnight, the server gets hit all at once. Spread them a few minutes apart.
  • Scheduling between 2 and 3 a.m. in a timezone with daylight saving time. On the night the clocks change, the job may be skipped or run twice.

A sample scenario

A developer sets up a nightly database backup and writes 0 2 * * *. The next morning, the backup shows a 5 a.m. timestamp. The server runs on UTC, while they're in Turkey, three hours ahead. To get 2 a.m. local time, the expression needs to be 0 23 * * *. After fixing it, they paste it into a validator to check the next few run times, and send the job's output to a log file so the next problem is easier to trace.

When to get help

If you're scheduling jobs across several servers, or jobs that depend on each other finishing first, cron alone may not be enough. Talk to a system administrator about a proper job scheduler or queue.