Automating Background Tasks with Cron
From database backups and cache warming to automated subscription renewals, SSL certificate provisioning, and report generation, scheduled background jobs are the backbone of backend engineering and cloud infrastructure. Since the early days of Unix in the 1970s, the cron daemon has been the universal standard for automated time-based job scheduling.
Yet even experienced staff engineers frequently consult syntax cheat sheets when authoring cron schedules. The subtle discrepancies between traditional 5-field POSIX crontab, 6-field Java/Spring Quartz cron, Kubernetes CronJobs, and AWS EventBridge schedules regularly lead to catastrophic production failures: jobs firing twice on daylight saving time transitions, overlapping jobs exhausting server memory, or jobs silently failing due to missing environment variables.
In this guide, we break down standard 5-part and 6-part cron syntax, explore non-standard shortcuts (@reboot, @daily), analyze cloud platform differences across Linux, Kubernetes, AWS, and GitHub Actions, and provide battle-tested techniques for reliable background task execution.
Build, explain, and preview upcoming run times visually with our free Cron Expression Generator.
Anatomy of the Standard 5-Field Linux Cron Expression
A standard Unix/Linux crontab entry consists of five space-separated temporal fields followed by the absolute shell command to execute:
┌───────────── Minute (0 - 59) │ ┌───────────── Hour (0 - 23) │ │ ┌───────────── Day of Month (1 - 31) │ │ │ ┌───────────── Month (1 - 12 or JAN - DEC) │ │ │ │ ┌───────────── Day of Week (0 - 6 or SUN - SAT, 0 = Sunday) │ │ │ │ │ * * * * * /usr/bin/python3 /opt/scripts/backup.py
The Four Core Operators:
- Asterisk (
*): Represents every possible value within the field.* * * * *fires at the start of every single minute. - Comma (
,): Specifies an explicit list of discrete values.0 8,12,18 * * *executes at 8:00 AM, 12:00 PM, and 6:00 PM. - Hyphen (
-): Defines an inclusive contiguous range.0 9-17 * * 1-5runs on the hour, every hour from 9 AM to 5 PM, Monday through Friday. - Forward Slash (
/): Specifies step intervals through a range.*/15 * * * *means execute every 15 minutes (:00,:15,:30,:45).
Non-Standard Predefined Cron Macros
Modern Vixie Cron, Cronie, and systemd cron implementations support convenient predefined string macros that replace the five numeric fields:
| Macro Shortcut | Equivalent Standard 5-Field Expression | Plain-English Schedule & Purpose |
|---|---|---|
@reboot | (None) | Executes once immediately after system boot-up. Ideal for bootstrapping background daemons. |
@yearly or @annually | 0 0 1 1 * | Runs once per year at midnight on January 1st. |
@monthly | 0 0 1 * * | Runs once per month at midnight on the 1st of the month. Ideal for billing runs. |
@weekly | 0 0 * * 0 | Runs once per week at midnight on Sunday morning. Ideal for log archiving. |
@daily or @midnight | 0 0 * * * | Runs once every day at midnight (00:00). Standard daily maintenance window. |
@hourly | 0 * * * * | Runs at minute 0 of every hour. Ideal for cache warming and health telemetry. |
Production Cron Recipes Cheat Sheet
| Desired Business Schedule | Cron Expression | Plain-English Schedule Translation |
|---|---|---|
| Every 5 Minutes | */5 * * * * | Fires at :00, :05, :10, :15, :20, :25, etc. |
| Every 10 Minutes on Weekdays | */10 * * * 1-5 | Fires every 10 minutes from Monday through Friday |
| Every 30 Minutes During Business Hours | 0,30 9-17 * * 1-5 | Fires at :00 and :30 between 9:00 AM and 5:30 PM, Mon-Fri |
| Every Day at 3:30 AM | 30 3 * * * | Low-traffic database backup and vacuum window |
| Twice a Month (1st & 15th) | 0 0 1,15 * * | Bi-weekly payroll calculation schedule |
| Quarterly Fiscal Close | 0 0 1 1,4,7,10 * | Runs on Jan 1, Apr 1, Jul 1, Oct 1 at midnight UTC |
| Every 2 Hours on Weekends | 0 */2 * * 0,6 | Fires at 0:00, 2:00, 4:00... on Saturday and Sunday |
The Subtle "Day of Month" vs. "Day of Week" Trap
One of the most dangerous and commonly misunderstood behaviors in standard POSIX crontab is specifying both Day of Month (Field 3) and Day of Week (Field 5):
# What does this schedule do? 0 0 15 * 5 /opt/scripts/security-audit.sh
Most software engineers assume this means: "Run on the 15th of the month ONLY IF it is a Friday".
This assumption is 100% false!
In POSIX standard crontab, when both Day of Month and Day of Week are explicitly specified (i.e., neither is an asterisk *), their logical relationship is OR, not AND!
- The job will fire on the 15th of the month.
- The job will also fire on every single Friday of the month!
How to Enforce an AND Condition in Linux:
To ensure a script runs exclusively when the 15th falls on a Friday, keep the crontab field general and test the day inside your shell command:
# Only executes if today is Friday (%u = 5) 0 0 15 * * [ $(date +%u) -eq 5 ] && /opt/scripts/security-audit.sh
Convert timestamps and inspect date formats using our Unix Timestamp Converter.
Multi-Platform Comparison: Linux vs. Kubernetes vs. AWS vs. Quartz
Different cloud systems and runtimes implement divergent cron parsers:
| Scheduler Platform | Field Count | Support for Seconds? | Support for Year? | Wildcard Handling | Key Operational Trap |
|---|---|---|---|---|---|
| Standard Linux (Vixie Cron) | 5 Fields | ❌ No | ❌ No | Standard POSIX (*, ,, -, /) | Limited non-interactive PATH environment |
| Kubernetes CronJob | 5 Fields | ❌ No | ❌ No | Standard POSIX | Overlapping pods without concurrencyPolicy |
| AWS EventBridge / CloudWatch | 6 Fields | ❌ No | ✅ Yes | Requires ? in Day-of-Month or Day-of-Week | Fails validation if * used in both day fields |
| Spring Framework / Quartz | 6 or 7 Fields | ✅ Yes (Field 1) | Optional (Field 7) | Supports L (Last) and W (Weekday) | First field is Seconds (0-59), not minutes! |
GitHub Actions (schedule) | 5 Fields | ❌ No | ❌ No | Standard POSIX | Runs exclusively in UTC; high queue delay during peak hours |
1. Kubernetes CronJob Concurrency Policies
When deploying scheduled workloads in Kubernetes, long-running batch jobs can easily overlap if the previous execution has not terminated before the next schedule fires. Always configure concurrencyPolicy:
apiVersion: batch/v1 kind: CronJob metadata: name: warehouse-inventory-sync spec: schedule: "*/15 * * * *" concurrencyPolicy: Forbid # Crucial: Drops new run if previous pod is still processing successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 5 jobTemplate: spec: template: spec: containers: - name: sync-worker image: registry.tryandtool.com/sync:latest restartPolicy: OnFailure
Allow(Default): Concurrent jobs run simultaneously, risking race conditions and database deadlocks.Forbid: If a previous job is still running, the scheduler skips the new execution entirely.Replace: Cancels the currently running job and launches the new one.
2. AWS EventBridge 6-Field Syntax
AWS EventBridge rules require exactly six fields:
cron(Minutes Hours Day-of-month Month Day-of-week Year)
Crucially, AWS mandates that you specify a question mark (?) in either Day-of-Month or Day-of-Week:
# Weekdays at 12:00 PM UTC every year: cron(0 12 ? * MON-FRI *)
Three Common Production Crontab Traps & Solutions
1. The Missing Environment Variable Trap
A common frustration among engineers is a script executing successfully in their interactive terminal but silently failing when run via crontab.
- Cause: When you log in interactively, your shell sources
~/.bashrc,~/.profile, and exports fullPATHvariables (such as/usr/local/binor~/.nvm/...). - Cron runs inside a minimal, non-interactive, non-login subshell with a default
PATH=/usr/bin:/bin. - Solution: Always specify absolute paths to binaries, or declare
PATHat the top of your crontab:
SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin MAILTO=devops-alerts@tryandtool.com 0 2 * * * /usr/local/bin/python3 /opt/app/cleanup.py >> /var/log/cleanup.log 2>&1
2. Preventing Overlapping Executions with flock
If a task scheduled every 5 minutes takes 8 minutes to complete due to heavy database load, cron will fire a second instance while the first is still running, compounding server degradation. Use Linux flock (file lock) to guarantee mutual exclusion:
# If lock /tmp/backup.lock is held, exit immediately (0) without running duplicate */5 * * * * /usr/bin/flock -n /tmp/backup.lock /opt/scripts/run-backup.sh
3. Daylight Saving Time (DST) Jumps
If your server timezone is set to local time (e.g., America/New_York), scheduled jobs face temporal anomalies twice a year:
- Spring Forward: The clock jumps from 1:59 AM directly to 3:00 AM. Any job scheduled between 2:00 AM and 2:59 AM is completely skipped!
- Fall Back: The clock rolls back from 2:00 AM to 1:00 AM. Any job scheduled between 1:00 AM and 1:59 AM runs twice!
- Rule of Thumb: Always configure server operating systems, container runtimes, and databases to UTC (Etc/UTC).
Format configuration payloads and JSON manifests using our JSON Formatter & Validator.
Frequently Asked Questions (FAQ)
Why did my cron job fail with "command not found" even though it works in my terminal?
When you run commands in your terminal, your shell loads environment variables from files like ~/.bashrc or ~/.zshrc, configuring your PATH to include Node.js, Python virtualenvs, or custom utilities. Crontab executes commands in an isolated, minimal subshell where PATH is typically restricted to /usr/bin:/bin. To resolve this, use absolute paths for both the interpreter and the script (e.g., /usr/bin/node /home/ubuntu/app/sync.js), or define the PATH variable at the top of your crontab file.
Can I schedule a cron job to run every 30 seconds?
Standard POSIX crontab has a minimum granularity of one minute; it does not natively support sub-minute intervals. To run a script every 30 seconds, you can either create two crontab entries where the second sleeps for 30 seconds:
* * * * * /usr/bin/php /opt/worker.php * * * * * sleep 30; /usr/bin/php /opt/worker.php
Alternatively, use a continuous background daemon managed by systemd with a systemd.timer configured with OnUnitActiveSec=30s.
What is the difference between system crontab (/etc/crontab) and user crontab (crontab -e)?
- User Crontab (
crontab -e): Associated with an individual user account. It contains 5 time fields followed by the command. The command automatically runs with that user's permissions. - System Crontab (
/etc/crontab): Contains 6 fields before the command. The 6th field explicitly defines the username that executes the command (e.g.,0 * * * * root /usr/sbin/logrotate).
Why are GitHub Actions scheduled workflows often delayed by 15 to 30 minutes?
GitHub Actions uses a shared virtual machine runner infrastructure. When hundreds of thousands of repositories configure workflows to trigger at the top of the hour (0 * * * *), GitHub's queue experiences massive scheduling contention. Scheduled workflows are given lower priority than interactive git push events, resulting in execution delays of 10 to 45 minutes during peak hours. If strict time precision is required, use AWS EventBridge or a dedicated webhook dispatcher.
What is the difference between standard cron and modern systemd timers?
Modern Linux distributions (Ubuntu, Debian, RHEL, CentOS) increasingly recommend systemd timers over cron. Systemd timers provide millisecond execution precision, integrate directly with journalctl for unified log aggregation, support dependency-based execution, and can automatically catch up on missed executions if the server was powered down during the scheduled window.
Generate, explain, and copy deployment syntax for Linux, Kubernetes, and AWS using our Cron Expression Generator.
