Cron job examples are ready-made scheduling patterns and commands that sysadmins can copy, adapt, and run via crontab to automate backups, updates, monitoring, and maintenance. Below are practical, production-tested cron job examples with best practices for reliability, security, and performance so your Linux servers run the right tasks on time, every time.
If you manage Linux servers, learning cron job examples is one of the highest-ROI skills you can build. Cron automates repetitive tasks—backups, log cleanup, SSL renewals, patching, and WordPress maintenance freeing you from manual chores and reducing risk. This guide distills 15+ years of sysadmin practice into safe, copy-paste crontab examples with explanations.
How Cron Works (Quick Primer)
Cron is a time-based job scheduler. The cron daemon reads system-wide and per-user crontab files, then executes commands at defined times. It’s simple, lightweight, and ubiquitous on Linux and Unix-like systems.
Where Cron Reads Jobs
Common locations include:
- User crontabs: managed via
crontab -e(stored under/var/spool/cron/) - System crontab:
/etc/crontab - Drop-in files:
/etc/cron.d/(package or service-specific) - Periodic directories:
/etc/cron.hourly,/etc/cron.daily,/etc/cron.weekly,/etc/cron.monthly
Crontab Syntax (Minute to Weekday)
Crontab uses five time fields followed by the command. Asterisks match all values; commas list values; dashes define ranges; slashes set steps.
# ┌─ minute (0-59)
# │ ┌─ hour (0-23)
# │ │ ┌─ day of month (1-31)
# │ │ │ ┌─ month (1-12)
# │ │ │ │ ┌─ day of week (0-7, Sun=0 or 7)
# │ │ │ │ │
# * * * * * command-to-run
# Special strings:
@reboot command
@yearly command
@monthly command
@weekly command
@daily command
@hourly command
Cron Best Practices Before You Start
Set Environment and Use Absolute Paths
Cron runs with a minimal environment. Always set PATH, use absolute paths, and log output. Prefer using a wrapper script for complex tasks.
# In your crontab (crontab -e)
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MAILTO=admin@example.com
# Log both stdout and stderr:
# command >> /var/log/cron/myjob.log 2>&1
Avoid Duplicate Runs with flock
Ensure only one instance runs at a time by locking the job. This prevents overlap on slow or busy servers.
*/5 * * * * flock -n /var/lock/myjob.lock /usr/local/bin/myjob.sh >> /var/log/cron/myjob.log 2>&1
Plan for Timezones, DST, and Non-24/7 Hosts
Schedule in UTC to avoid DST surprises. For laptops or VMs that don’t run 24/7, use anacron. On modern distros, consider systemd timers for richer control and calendar semantics.
Privilege and Security
Run as the least-privileged user possible, sanitize inputs, quote variables, and avoid shell wildcards that may expand unpredictably. Keep secrets in root-readable files and reference them securely.
Top Cron Job Examples for Sysadmins
1) Nightly Server Backups (rsync)
Mirror key directories to a backup disk or NAS. Combine with rotation (e.g., via date-stamped dirs) and offsite sync.
0 2 * * * flock -n /var/lock/backup.lock rsync -aHAX --delete /srv/ /backup/srv/ >> /var/log/cron/backup.log 2>&1
2) Encrypted Incremental Backups (Restic)
Push encrypted snapshots to object storage (S3, B2). Ensure environment variables are set via a sourced file.
15 2 * * * . /root/.restic-env; flock -n /var/lock/restic.lock restic backup /var/www /etc --verbose && restic forget --keep-daily 7 --keep-weekly 4 --prune >> /var/log/cron/restic.log 2>&1
3) MySQL/MariaDB Hot Dumps
Create compressed, dated dumps and prune old ones. Store credentials in /root/.my.cnf with strict permissions.
30 1 * * * mkdir -p /backup/db && mysqldump --all-databases | gzip > /backup/db/mysql-$(date +\%F).sql.gz && find /backup/db -name 'mysql-*.sql.gz' -mtime +14 -delete
4) PostgreSQL Dumps
Use pg_dumpall or per-database pg_dump. Ensure proper PG environment variables or .pgpass file.
40 1 * * * mkdir -p /backup/db && pg_dumpall -U postgres | gzip > /backup/db/postgres-$(date +\%F).sql.gz && find /backup/db -name 'postgres-*.sql.gz' -mtime +14 -delete
5) Let’s Encrypt Certificate Renewal (Certbot)
Renew SSL certificates twice daily and reload the web server if renewal occurs. Many distros install a timer, but cron works too.
0 */12 * * * certbot renew --quiet --deploy-hook "systemctl reload nginx"
6) Unattended Security Updates
On Debian/Ubuntu, prefer unattended-upgrades. If you must use cron, schedule updates and log output.
20 3 * * * apt-get update && DEBIAN_FRONTEND=noninteractive apt-get -y upgrade >> /var/log/cron/apt-updates.log 2>&1
7) Log Rotation Trigger (if needed)
Most systems rotate logs via logrotate and system timers. If you need a manual cron trigger, use:
0 0 * * * /usr/sbin/logrotate -s /var/lib/logrotate/status /etc/logrotate.conf >> /var/log/cron/logrotate.log 2>&1
8) Disk Usage Alerts
Send an email when disk usage exceeds a threshold. Adjust the percentage as needed.
*/15 * * * * df -hP | awk 'NR>1 {if (int($5)>85) print $0}' | mail -s "Disk Alert on $(hostname)" admin@example.com
9) Systemd Service Health Checks with Auto-Restart
Monitor critical services and restart if they’re inactive. Combine with alerting for visibility.
*/5 * * * * systemctl is-active --quiet nginx || (systemctl restart nginx && echo "Nginx restarted on $(hostname)" | mail -s "Nginx Restarted" admin@example.com)
10) Clean Temporary and Cache Files
Keep temp and cache directories tidy to reclaim space. Be precise with paths to avoid accidental deletions.
30 3 * * * find /tmp -type f -mtime +3 -delete
0 4 * * 0 find /var/cache -type f -mtime +7 -delete
11) Journal Cleanup
Prune systemd journal to a sane size and age, keeping logs manageable.
15 4 * * * journalctl --vacuum-size=1G --vacuum-time=14d
12) Docker Image and Container Pruning
Remove unused Docker resources weekly to save disk space. Review before enabling on production hosts.
0 5 * * 0 docker system prune -af --volumes >> /var/log/cron/docker-prune.log 2>&1
13) rsync to Offsite Host
Push critical data to an offsite server over SSH with keys and restricted permissions. Consider bandwidth windows.
0 1 * * * rsync -a --delete -e "ssh -i /root/.ssh/backup_key" /backup/ backupuser@offsite.example.com:/offsite/$(hostname)/
14) Security Scans (ClamAV)
Perform daily antivirus scans of web roots and quarantine infected files for review.
30 2 * * * clamscan -ri /var/www --log=/var/log/clamav/daily_scan.log --move=/var/quarantine/
15) Configuration Drift Detection
Detect unauthorized changes with checksums of key directories and email differences.
*/30 * * * * (cd /etc && sha256sum -b $(find . -type f) | sort | sha256sum) | diff -q - /root/.etc.sha256 || (echo "Config drift on $(hostname)" | mail -s "Config Drift" admin@example.com); (cd /etc && sha256sum -b $(find . -type f) | sort | sha256sum > /root/.etc.sha256)
WordPress-Friendly Cron Job Examples
Replace WP-Cron with System Cron
Disable pseudo-cron (DISABLE_WP_CRON) and schedule real cron for consistent performance, especially on busy sites or low-traffic sites where WP-Cron is unreliable.
# In wp-config.php
define('DISABLE_WP_CRON', true);
# System cron (every 5 minutes):
*/5 * * * * php -q /var/www/example.com/public/wp-cron.php >> /var/log/cron/wp-cron.log 2>&1
Scheduled WordPress Tasks with WP-CLI
Trigger scheduled events and maintenance safely via WP-CLI. Useful for multisite or multiple installs.
*/10 * * * * /usr/local/bin/wp --path=/var/www/example.com/public cron event run --due-now >> /var/log/cron/wp-events.log 2>&1
0 3 * * 0 /usr/local/bin/wp --path=/var/www/example.com/public cache flush
If you host WordPress on YouStable’s managed VPS or cloud, our team can harden WP-Cron, configure WP-CLI tasks, and set up offsite backups with retention—so your jobs run fast and predictably.
Advanced Scheduling Patterns
Avoid Thundering Herd: Randomize Start
When many servers run the same job, add a random delay to spread load. Use sleep with a random number.
*/5 * * * * sleep $((RANDOM % 300)); /usr/local/bin/metrics-push.sh
Every N Minutes or Specific Windows
Run every 15 minutes during business hours only, and hourly otherwise, by combining entries. Cron supports step values with ranges.
# Every 15 minutes 09:00–17:59
*/15 9-17 * * * /usr/local/bin/report.sh
# Hourly outside business hours
0 0-8,18-23 * * * /usr/local/bin/report.sh
Use @reboot for One-Time Boot Tasks
Initialize caches or verify mounts after boot. Pair with flock to avoid accidental multiple runs during rapid restarts.
@reboot flock -n /var/lock/boot-init.lock /usr/local/sbin/boot-init.sh
Troubleshooting Cron Jobs
Common Gotchas and Fixes
- Environment mismatch: export PATH, set SHELL, and source env files if needed.
- Permissions: ensure scripts are executable and owned by the correct user.
- Shell differences: use
/bin/bashif relying on Bash-isms. - Logging: always capture stdout and stderr to a named log.
- Mail alerts: use
MAILTOor send mail on nonzero exit codes. - Check logs:
/var/log/syslogor/var/log/crondepending on distro, and systemd’sjournalctl -u cronor-u crond.
# Test as the target user:
sudo -u www-data /usr/local/bin/script.sh
# Run the exact crontab command manually:
SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin command-here
Cron vs. Alternatives
Cron is lightweight and universal, but systemd timers offer richer calendars, dependencies, and native logging. In containers and Kubernetes, prefer init systems or Kubernetes CronJobs. For cross-cloud workflows, use providers like Cloud Scheduler (GCP) or EventBridge Scheduler (AWS).
When to Use Managed Help
If uptime is critical, offload cron design and monitoring to experts. YouStable’s managed hosting can architect resilient schedules (locks, retries, alerts), hardened backups, and safe update pipelines—so your automation is reliable, audited, and documented.
FAQs
What are the most useful cron job examples for Linux servers?
Backups (rsync/restic), database dumps, SSL renewals (certbot), security updates, disk and service health checks, log cleanup, Docker pruning, and WordPress WP-CLI schedules. Start with backups, monitoring, and patching for the biggest impact.
How do I run a cron job every 5 minutes safely?
Use */5 * * * *, add flock to prevent overlap, and log output. In fleets, randomize start with sleep $((RANDOM % 300)) to reduce load spikes.
Why does my script work manually but not from cron?
Environment differences: PATH, SHELL, and working directory vary under cron. Use absolute paths, specify the shell, set PATH, and capture errors with 2>&1. Test as the cron user with sudo -u <user>.
Should I use systemd timers instead of cron?
For complex schedules, dependencies, and native logging, yes—systemd timers are often superior. Cron remains excellent for simple, portable tasks and in environments without systemd.
How do I send email alerts from cron jobs?
Set MAILTO in crontab or pipe output to mail/mailx. Ensure an MTA (Postfix/ssmtp/msmtp) is configured. For example: ... | mail -s "Subject" admin@example.com.