Introduction
Scheduled tasks are essential for backup, report generation, cache cleanup, and health checks. cron is the classic Linux solution; systemd timer is the modern alternative.
systemd timers offer journal integration, dependency management, and monotonic clock advantages.
This guide compares both methods and provides production recommendations.
crontab Syntax
crontab -e edits user crontab. /etc/crontab system-wide. Five fields: minute hour day month weekday command.
*/5 * * * * every 5 minutes. 0 2 * * * daily at 02:00. @reboot runs at boot.
# Kullanıcı crontab
crontab -e
# Örnekler
0 3 * * * /opt/backup/backup.sh
*/15 * * * * /opt/healthcheck.sh
0 0 1 * * /opt/reports/monthly.shCron Environment and Security
Cron runs with minimal environment; use full paths. MAILTO for error email (usually redirect to journal).
Use set -euo pipefail in scripts. Cron files should be permission 600.
#!/bin/bash
set -euo pipefail
export PATH=/usr/local/bin:/usr/bin:/bin
cd /opt/myapp
./manage.py cleanup_sessionssystemd Timer Unit
.timer and .service pair required. OnCalendar=*-*-* 02:00:00 cron equivalent. Persistent=true catches up missed runs.
AccuracySec=1min delay tolerance. RandomizedDelaySec load spreading.
# backup.timer
[Unit]
Description=Daily backup
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.targetTimer Service Unit
.service unit runs the actual command. Type=oneshot for one-shot tasks. User=deploy for least privilege.
systemctl enable --now backup.timer activates the timer.
# backup.service
[Unit]
Description=Backup job
[Service]
Type=oneshot
User=backup
ExecStart=/opt/backup/backup.shCron vs systemd Timer
Cron: simple, universal, known everywhere. Timer: journal logs, dependencies, resource limits, monotonic clock.
Prefer systemd timer for new projects; existing cron scripts keep working.
Kritik görevlerde çift tetikleme (cron + timer) kullanmayın; tek mekanizma seçin.
Monitoring and Error Handling
systemctl list-timers --all shows timer status. journalctl -u backup.service last run logs.
Failed cron jobs can fail silently; always add logging and alerting.
- Tam yol kullanın
- set -euo pipefail
- Log ve alert
- Timer için Persistent=true
- Düzenli list-timers kontrolü
Conclusion
Both cron and systemd timer are valid; timer is advantageous on modern distributions. Keep tasks in version control and test them.
Alerting is mandatory for backup and critical tasks.