Understanding Cron Expressions
How the little five-field format for scheduling recurring tasks works.
Cron is the time-based job scheduler that ships with Unix-like systems. Its job is to run commands or scripts on their own, at the times or intervals you choose. You tell it when using a compact string called a cron expression, and that little string is what this article is about. There's a cron parser on this site if you'd like to test an expression as you read.
The five fields
A standard cron expression is just five fields separated by spaces. Read left to right, they're the minute, the hour, the day of the month, the month, and the day of the week. So 30 8 * * 1 means 8:30 in the morning, every Monday. Each field has its own range: minutes run 0 to 59, hours 0 to 23, day of the month 1 to 31, month 1 to 12, and day of the week usually 0 to 6.
Special characters
A few special characters do most of the work. The asterisk stands for every possible value in a field. A comma lists several specific values, like 1,15 for the first and the fifteenth. A hyphen marks a range, like 1-5 for a stretch of values. And a forward slash sets a step, so */15 in the minute field means every fifteen minutes. Mix and match these and you can describe a surprising range of schedules in very little space.
Examples
A few examples make it concrete. 0 * * * * fires at the top of every hour. 0 0 * * * runs once a day, at midnight. 0 9 * * 1-5 runs at nine in the morning on weekdays. And */10 * * * * goes off every ten minutes. When an expression looks puzzling, walking through the fields one at a time, in order, almost always untangles it.
Common considerations
A couple of things tend to catch people out. When you set both the day-of-month and the day-of-week fields, many cron implementations run the task if either one matches, not only when both do, which isn't always what you'd expect. The scheduler's time zone matters too, and it can really matter for anything tied to local time. Before you trust a schedule in production, it's worth double-checking it, say with a tool that restates it in plain language or shows the next few run times.
Summary
To wrap up, a cron expression uses five fields to say when a recurring task should run: minute, hour, day of the month, month, and day of the week. Special characters like the asterisk, comma, hyphen, and slash give you flexible schedules. Get comfortable with the fields and check the result before relying on it, and your tasks will run when you mean them to.