Skip to content
LangStop

Glossary

Keyboard Shortcuts

ActionShortcut
Toggle SidebarCtrl+B
Save TabCtrl+S
Close TabAlt+W
Switch to Tab 1Alt+Shift+1
Switch to Tab 2Alt+Shift+2
Switch to Tab 3Alt+Shift+3
Switch to Tab 4Alt+Shift+4
Switch to Tab 5Alt+Shift+5
Switch to Tab 6Alt+Shift+6
Switch to Tab 7Alt+Shift+7
Switch to Tab 8Alt+Shift+8
Switch to Tab 9Alt+Shift+9

What is Cron? — Cron Jobs & Scheduling Explained

Definition

Cron is a time-based job scheduler in Unix-like operating systems. It runs background tasks (called cron jobs) at specified dates, times, or intervals. The name comes from the Greek word chronos (χρόνος), meaning time. Cron is driven by a configuration file called a crontab (cron table), which lists commands and their scheduled execution times.

Cron runs as a long-running daemon process (crond) that wakes every minute, scans all crontab files, and executes any jobs whose scheduled time matches the current system time.


Cron Expression Syntax

A cron expression uses five space-separated fields to define a schedule:

Field Range Allowed Special Characters
Minute 0-59 * , - /
Hour 0-23 * , - /
Day of Month 1-31 * , - / L W
Month 1-12 or JAN-DEC * , - /
Day of Week 0-7 or SUN-SAT (0 and 7 = Sunday) * , - / L #

Special Characters

Character Meaning Example
* Wildcard — matches every value * * * * * = every minute
, List — separates multiple values 0,30 * * * * = at and
- Range — defines a range of values 0 9-17 * * * = every hour 9 AM–5 PM
/ Step — skips every N units */15 * * * * = every 15 minutes
L Last — last day of month/week 0 0 L * * = midnight on last day
W Weekday — nearest weekday 0 0 15W * * = nearest weekday to 15th
# Nth occurrence 0 0 * * 2#1 = first Tuesday of month

Common Cron Expression Examples

Expression Human-Readable
* * * * * Every minute
*/5 * * * * Every 5 minutes
*/15 * * * * Every 15 minutes
0 * * * * Every hour (at minute 0)
0 */2 * * * Every 2 hours
0 0 * * * Daily at midnight
0 6 * * * Daily at 6 AM
30 2 * * * Daily at 2 AM
0 0 * * 0 Weekly at midnight on Sunday
0 0 * * 1-5 Weekdays at midnight (Mon–Fri)
0 9-17 * * 1-5 Every hour 9 AM–5 PM on weekdays
0 0 1 * * First day of every month at midnight
0 0 1 1 * January 1st at midnight (yearly)
*/10 * * * 1-5 Every 10 minutes on weekdays
0 0 * * 1 Weekly on Monday at midnight

Special Strings

Cron provides shorthand strings that expand to standard expressions:

String Expansion Meaning
@yearly (or @annually) 0 0 1 1 * Run once a year at midnight on January 1
@monthly 0 0 1 * * Run once a month at midnight on the 1st
@weekly 0 0 * * 0 Run once a week at midnight on Sunday
@daily (or @midnight) 0 0 * * * Run once a day at midnight
@hourly 0 * * * * Run once an hour at the start of the hour
@reboot Run once when the system starts

These special strings are supported by most modern cron implementations (Vixie cron, cronie, anacron).


Crontab File Format

A crontab file contains one job per line in the following format:

MIN HOUR DOM MON DOW   COMMAND

Example Crontab

# ── System Maintenance ──────────────────────────────
0 3 * * 0   apt update && apt upgrade -y       # Weekly system update (Sunday 3 AM)
0 2 * * *   find /tmp -type f -atime +7 -delete  # Daily cleanup of old temp files
 
# ── Backups ──────────────────────────────────────────
0 1 * * 6   /usr/local/bin/backup-db.sh          # Weekly database backup (Saturday 1 AM)
30 23 * * *  tar -czf /backups/logs-$(date +\%Y\%m\%d).tar.gz /var/log/myapp  # Daily log archive
 
# ── Monitoring ───────────────────────────────────────
*/5 * * * *  /usr/local/bin/check-disk-space.sh  # Check disk usage every 5 minutes
0 * * * *    /usr/local/bin/ping-metrics.sh       # Send uptime metrics every hour
 
# ── Special Strings ──────────────────────────────────
@daily   /usr/local/bin/rotate-logs.sh           # Rotate logs daily
@reboot  /usr/local/bin/start-app.sh             # Start application on boot

Crontab Management Commands

Command Description
crontab -l List current user's crontab
crontab -e Edit crontab with default editor
crontab -r Remove current user's crontab
sudo crontab -u username -l List another user's crontab (requires root)
crontab /path/to/file Install crontab from file

Common Cron Use Cases

Automated Backups

Schedule database dumps and file backups during off-peak hours (e.g., 1 AM) to minimize impact on production systems.

Log Rotation and Cleanup

Automatically archive, compress, or delete old log files to prevent disk space exhaustion.

Report Generation

Generate and email periodic reports — daily sales summaries, weekly analytics dashboards, monthly billing statements.

System Monitoring

Run health checks every few minutes to verify services are running, disk usage is within limits, and certificates have not expired.

Data Synchronization

Scheduled sync jobs between databases, file servers, or cloud storage buckets (e.g., hourly ETL pipelines).

Certificate Renewal

Run certbot or similar tools via cron to auto-renew TLS/SSL certificates before they expire.


Cron Best Practices

1. Always Redirect Output

Cron sends unredirected output to the system mail spool. Explicitly redirect stdout and stderr to a log file:

0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

2. Use Absolute Paths

Cron jobs run with a minimal environment (often a restricted PATH). Always use full paths:

0 3 * * * /usr/bin/find /tmp -type f -atime +7 -delete

3. Implement Idempotency

Design jobs so they produce the same outcome regardless of how many times they run. Use LOCK files or scripts that check state before acting.

4. Add Error Handling

Wrap commands in scripts with proper error handling and exit codes:

#!/bin/bash
set -euo pipefail
# ... job logic ...

5. Monitor Job Execution

Track whether jobs complete successfully using:

  • Exit code logging
  • Healthcheck services (e.g., cron monitoring tools)
  • Prometheus metrics for job duration and success rate

6. Avoid Overlapping Runs

For jobs that may take longer than their interval, use file-based locking:

#!/bin/bash
LOCKFILE=/tmp/backup.lock
if [ -f "$LOCKFILE" ] && kill -0 $(cat "$LOCKFILE") 2>/dev/null; then
  echo "Job already running"
  exit 1
fi
echo $$ > "$LOCKFILE"
trap 'rm -f "$LOCKFILE"' EXIT
# job logic...

7. Test Expressions Before Deploying

Use an interactive cron helper to validate expressions and preview next execution times before writing them to production crontabs.


Modern Alternatives

While cron remains the standard scheduler on Unix systems, several modern alternatives address cron's limitations (no second-level precision, no dependency tracking, no centralized management).

Alternative Description Best For
systemd Timers Built into modern Linux distributions. Offers calendar-based and monotonic scheduling, persistent timers, dependency management, and detailed logging. Linux servers using systemd
Kubernetes CronJobs Native Kubernetes resource for running batch jobs on a schedule. Supports concurrency policies, job history limits, and deadline thresholds. Containerized workloads on Kubernetes
CI/CD Schedulers GitHub Actions scheduled workflows, GitLab CI pipeline schedules, Jenkins cron triggers. Development pipelines and automated builds
Anacron Handles jobs for systems that do not run 24/7 (e.g., laptops). Ensures missed jobs run at startup. Desktops and laptops
Apache Airflow DAG-based workflow scheduler with retries, alerting, and a web UI. Complex data pipelines with dependencies
AWS EventBridge / CloudWatch Cloud-native scheduling with Lambda and ECS integration. Supports cron and rate expressions. AWS cloud infrastructure

systemd Timer Example

# /etc/systemd/system/backup.timer
[Unit]
Description=Daily database backup timer
 
[Timer]
OnCalendar=daily
Persistent=true
 
[Install]
WantedBy=timers.target
# /etc/systemd/system/backup.service
[Unit]
Description=Database backup service
 
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup-db.sh

Kubernetes CronJob Example

apiVersion: batch/v1
kind: CronJob
metadata:
  name: database-backup
spec:
  schedule: "0 2 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: backup-tool:latest
            command: ["/backup.sh"]
          restartPolicy: OnFailure

LangStop Cron Tools

Related Tools

Try these complementary developer tools: