1. Home
  2. Blog
  3. DevOps

DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron runs commands on a schedule: backups at 2 a.m., reports every Monday, cleanups every 15 minutes. The five-field syntax is short but easy to misread. We calculated the next run times for real expressions to show exactly what each one does.

10 min read
Cron jobs explained: syntax, real schedules and the mistakes that break them

Key takeaways

  • A cron expression has five fields: minute, hour, day of month, month, day of week.
  • * means every, , lists values, - sets a range, and / sets a step.
  • If both day fields are restricted, cron runs when either matches, not both.
  • Most “it works by hand but not in cron” problems are about PATH, the working directory or missing environment variables.

A nightly backup has quietly not run for three weeks. The script works perfectly when run by hand. The cron entry looks right. This is the most common cron story, and it almost always comes down to a handful of predictable mistakes. Once you know them, cron is one of the simplest and most reliable tools in operations.

To show precisely when each schedule fires, we calculated the next run times with the croniter 6.2 Python library, starting from Monday 9 November 2026 at 10:07. We did not run a cron daemon for this article; the crontab and shell snippets are standard examples, not output from our machine.

What is cron?

Cron is a time-based job scheduler found on Linux, macOS and other Unix-like systems. A background service, the cron daemon, wakes up every minute, checks each user’s schedule table, called a crontab, and runs any command whose time matches. The same five-field expression format is also used by Kubernetes CronJobs, GitHub Actions schedules and many cloud schedulers.

The five fields

┌───────── minute        (0-59)
│ ┌─────── hour          (0-23)
│ │ ┌───── day of month  (1-31)
│ │ │ ┌─── month         (1-12 or JAN-DEC)
│ │ │ │ ┌─ day of week   (0-6, Sunday = 0, or SUN-SAT)
│ │ │ │ │
* * * * *  command to run

Many systems also accept 7 for Sunday. Names such as MON-FRI work in most implementations; our validator accepted 0 9 * * MON-FRI and rejected 61 * * * *, since minutes stop at 59.

Operators

Symbol Meaning Example
* Every value * * * * * every minute
, List 0 0 1,15 * * on the 1st and 15th
- Range 30 9 * * 1-5 weekdays
/ Step */15 * * * * every 15 minutes

Steps count from the start of the range. */15 in the minute field means minutes 0, 15, 30 and 45, not “15 minutes after the last run”. Extra symbols such as L (last), W (weekday) and # (nth weekday) come from Quartz and some cloud schedulers; standard Linux cron does not support them.

Verified examples

Here are common expressions with the next three run times we calculated from Monday 09 Nov 10:07:

Expression Meaning Next runs
*/15 * * * * Every 15 minutes Mon 10:15, 10:30, 10:45
0 2 * * * Daily at 02:00 Tue 10 Nov, Wed 11 Nov, Thu 12 Nov 02:00
30 9 * * 1-5 Weekdays at 09:30 Tue, Wed, Thu 09:30
0 */6 * * * Every 6 hours Mon 12:00, Mon 18:00, Tue 00:00
0 0 1,15 * * 1st and 15th at midnight Sun 15 Nov, Tue 01 Dec, Tue 15 Dec
0 3 * * 0 Sundays at 03:00 15, 22, 29 Nov
59 23 31 * * The 31st at 23:59 31 Dec, 31 Jan, 31 Mar

Two details are worth noticing. “Weekdays at 09:30” skipped Monday 9 November, because 09:30 had already passed at 10:07. And the “31st” job skipped November and February entirely, because those months have no 31st. Cron does not move it to the last day of the month. For a true month-end job, run on days 28 to 31 and let the script check whether tomorrow is the 1st.

The day-of-month and day-of-week trap

Suppose you want a job on the 1st of the month, but only if it is a Monday, and you write 0 9 1 * 1. Here is what it actually does:

0 9 1 * 1  ->  Mon 16 Nov, Mon 23 Nov, Mon 30 Nov, Tue 01 Dec, Mon 07 Dec, Mon 14 Dec

It runs on every Monday and on the 1st of every month. When both day fields are restricted, traditional cron treats them as OR. This surprises almost everyone. With croniter’s AND mode switched on, the same expression gave Mon 01 Feb 2027, Mon 01 Mar 2027 and Mon 01 Nov 2027, which is probably what was meant, but standard cron does not behave that way. The reliable approach is to schedule the wider condition and check the other inside the script, for example run every Monday and exit unless the date is 1 to 7 for “first Monday of the month”.

@daily and other shortcuts

Shortcut Equivalent
@hourly 0 * * * *
@daily / @midnight 0 0 * * *
@weekly 0 0 * * 0
@monthly 0 0 1 * *
@yearly / @annually 0 0 1 1 *
@reboot Once when the cron daemon starts

Shortcuts are readable, but they all fire at midnight. If many servers or jobs use @daily, they all start at the same moment, which can overload a shared database or API. Spreading start times, such as 17 2 * * *, avoids that spike.

Editing a crontab

crontab -e     # edit your crontab
crontab -l     # list it
crontab -r     # remove it entirely (careful!)

Each line is one job. Lines starting with # are comments; use them to say what each job does and who owns it. crontab -r sits right next to -e on the keyboard and deletes everything without asking, so keep a copy of important crontabs in version control. System-wide jobs live in /etc/crontab and /etc/cron.d/, where lines include an extra user field before the command.

Why jobs work by hand but not in cron

Cron runs commands with a very small environment, not your login shell. The usual culprits:

  • PATH: cron’s PATH is often just /usr/bin:/bin, so tools in /usr/local/bin or a virtual environment are not found. Use full paths, such as /usr/bin/python3 or the venv’s own Python.
  • Working directory: jobs usually start in the user’s home directory. Relative paths like ./data/report.csv point to the wrong place. cd first or use absolute paths.
  • Environment variables: variables from your .bashrc are not loaded. Set them in the crontab or in a wrapper script; see our environment variables guide.
  • Shell: cron uses /bin/sh by default, not bash, so bash-only syntax fails.
  • The percent sign: in a crontab line, % means a newline and must be escaped as \%. This breaks date +%Y-%m-%d in many first attempts.
  • Permissions: the job runs as the crontab’s owner, who may not be able to read the files you expect.
# A safer crontab entry (example, not run for this article)
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=ops@example.com

17 2 * * * cd /srv/shop && ./venv/bin/python backup.py >> /var/log/shop/backup.log 2>&1

Logging and alerts

By default, cron emails any output to the job’s owner, which on most servers goes nowhere. Redirect output to a log file, as above, with 2>&1 so errors are captured too. Inside the script, use proper logging with timestamps, as in our Python logging guide. Most importantly, alert on silence: a failed job may produce an error, but a job that never runs produces nothing. “Dead man’s switch” monitors, where the job pings a URL on success and an alert fires if the ping does not arrive, catch both.

Tip: Before relying on a new schedule, run the exact command from the crontab with env -i /bin/sh -c '...'. Running it with an empty environment reproduces most of the problems cron will hit, while you are still watching.

Overlapping runs

If a job scheduled every 5 minutes sometimes takes 7, two copies will run at once, which can corrupt files or double-process data. Wrap the command with flock, for example flock -n /tmp/sync.lock ./sync.sh, so a second copy exits immediately if the first still holds the lock. Making jobs idempotent, so running them twice is harmless, gives you a second layer of safety, and an upsert is a common way to achieve that for database writes.

Time zones and daylight saving

Cron uses the server’s time zone, which on cloud servers is usually UTC. A job set for 09:00 may fire at 14:30 local time in India. In regions with daylight saving time, a job scheduled between 02:00 and 03:00 can be skipped or run twice on the days the clocks change. Prefer UTC on servers, avoid scheduling important jobs in the changeover hour, and document the time zone next to each job. Some cron implementations support a CRON_TZ variable; check your system before relying on it.

Cron in modern platforms

  • Kubernetes CronJobs use the same five fields and add a concurrencyPolicy setting to prevent overlaps.
  • GitHub Actions supports on: schedule with cron syntax, always in UTC, and scheduled runs can be delayed at busy times. See our GitHub Actions guide.
  • systemd timers on Linux offer logging, dependencies and catch-up of missed runs.
  • Cloud schedulers from AWS, Google Cloud and Azure trigger functions or containers without a server to manage.

Whatever runs the schedule, the habits are the same: absolute paths, captured output, overlap protection, alerts on missed runs and clear ownership.

Final thoughts

Cron’s five fields are easy to learn and easy to misread. Check every new expression with a calculator or library before trusting it, watch out for the day-of-month OR day-of-week rule and months without a 31st, and write jobs that use absolute paths, log their output and cannot overlap. Then add an alert for the job that silently stops running, because that is the failure you would otherwise discover weeks later.

Frequently asked questions

What do the five fields in a cron expression mean?

In order: minute (0-59), hour (0-23), day of month (1-31), month (1-12) and day of week (0-6, with Sunday as 0).

How do I run a cron job every 5 minutes?

Use */5 * * * *. It runs at minutes 0, 5, 10 and so on, every hour of every day.

Why does my cron job not run?

Common causes are a missing PATH or environment variables, relative file paths, unescaped % signs, permissions, or a schedule that does not mean what you expected. Redirect output to a log to see errors.

What happens if both day fields are set?

Traditional cron runs the job when either the day of month or the day of week matches. In our test, 0 9 1 * 1 ran every Monday and on the 1st of each month.

What time zone does cron use?

The server’s local time zone, which is often UTC on cloud servers. Check it with the date command and document it beside each job.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →