Cron ist der Standard-Taskplaner unter Linux. Er führt Befehle und Skripte zu festgelegten Zeiten automatisch aus - ideal für Backups, Wartung und wiederkehrende Aufgaben.

Cron-Syntax

Crontab-Format

┌───────────── Minute (0-59)
│ ┌───────────── Stunde (0-23)
│ │ ┌───────────── Tag des Monats (1-31)
│ │ │ ┌───────────── Monat (1-12)
│ │ │ │ ┌───────────── Wochentag (0-7, 0 und 7 = Sonntag)
│ │ │ │ │
* * * * * Befehl

Spezialzeichen

ZeichenBedeutung
*Jeder Wert
,Liste (1,3,5)
-Bereich (1-5)
/Schrittweite (*/15)

Vordefinierte Zeitangaben

KürzelEntspricht
@rebootBeim Systemstart
@yearly0 0 1 1 *
@monthly0 0 1
@weekly0 0 0
@daily0 0 *
@hourly0

Crontab verwalten

Benutzer-Crontab

# Crontab bearbeiten
crontab -e

# Crontab anzeigen
crontab -l

# Crontab löschen
crontab -r

# Crontab eines anderen Users (root)
crontab -u username -e

System-Crontabs

# /etc/crontab - System-weite Crontab
# /etc/cron.d/ - Zusätzliche Crontabs
# /etc/cron.daily/ - Tägliche Scripts
# /etc/cron.hourly/ - Stündliche Scripts
# /etc/cron.weekly/ - Wöchentliche Scripts
# /etc/cron.monthly/ - Monatliche Scripts

Beispiele

Zeitpläne

# Jede Minute
* * * * * /path/to/script.sh

# Alle 5 Minuten
*/5 * * * * /path/to/script.sh

# Stündlich um :30
30 * * * * /path/to/script.sh

# Täglich um 3:00
0 3 * * * /path/to/script.sh

# Montags um 9:00
0 9 * * 1 /path/to/script.sh

# Jeden 1. des Monats um 0:00
0 0 1 * * /path/to/script.sh

# Werktags (Mo-Fr) um 8:00
0 8 * * 1-5 /path/to/script.sh

# Alle 15 Minuten während Arbeitszeit
*/15 8-17 * * 1-5 /path/to/script.sh

Praktische Jobs

# Backup täglich um 2:00
0 2 * * * /usr/local/bin/backup.sh

# Log-Rotation wöchentlich
0 0 * * 0 /usr/sbin/logrotate /etc/logrotate.conf

# SSL-Zertifikate erneuern (2x täglich)
0 0,12 * * * certbot renew --quiet

# Datenbank-Dump täglich
0 3 * * * mysqldump -u root mydb > /backup/mydb-$(date +\%Y\%m\%d).sql

# Temp-Dateien aufräumen
0 4 * * * find /tmp -type f -mtime +7 -delete

# System-Update (Debian)
0 5 * * 0 apt update && apt upgrade -y

Ausgabe und Logging

Mail-Benachrichtigung

# Mail-Empfänger setzen
MAILTO=admin@example.de

# Keine Mail
MAILTO=""

# Job mit spezifischer Mail
0 3 * * * /backup.sh 2>&1 | mail -s "Backup Report" admin@example.de

In Datei loggen

# stdout und stderr
0 3 * * * /backup.sh >> /var/log/backup.log 2>&1

# Mit Timestamp
0 3 * * * echo "$(date): Starting backup" >> /var/log/backup.log && /backup.sh >> /var/log/backup.log 2>&1

# Nur Fehler
0 3 * * * /backup.sh >> /dev/null 2>> /var/log/backup-errors.log

Keine Ausgabe

0 3 * * * /backup.sh > /dev/null 2>&1

Umgebungsvariablen

In Crontab setzen

# Am Anfang der Crontab
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
HOME=/root
MAILTO=admin@example.de

# Jobs
0 3 * * * /backup.sh

Im Script laden

#!/bin/bash
# /usr/local/bin/backup.sh

# Umgebung laden
source /etc/environment
source ~/.bashrc

# Oder explizit
export PATH=/usr/local/bin:$PATH
export LANG=de_DE.UTF-8

# Rest des Scripts

Cron-Verzeichnisse

/etc/cron.d/

# /etc/cron.d/myapp
# Format: wie /etc/crontab mit User-Feld

SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin

*/5 * * * * www-data /var/www/myapp/cron.php
0 3 * * * root /usr/local/bin/myapp-backup.sh

/etc/cron.daily/

#!/bin/bash
# /etc/cron.daily/cleanup
# Keine Zeitangabe nötig - wird täglich ausgeführt

find /var/log -name "*.log" -mtime +30 -delete
chmod +x /etc/cron.daily/cleanup

Best Practices

Locking (Keine Überlappung)

#!/bin/bash
# Mit flock

LOCKFILE=/var/run/backup.lock

exec 200>$LOCKFILE
flock -n 200 || exit 1

# Backup-Code hier
/backup/script.sh
# In Crontab mit flock
0 3 * * * flock -n /var/run/backup.lock /backup.sh

Fehlerbehandlung

#!/bin/bash
set -e  # Bei Fehler abbrechen

# Oder mit Trap
trap 'echo "Fehler in Zeile $LINENO" | mail -s "Cron Error" admin@example.de' ERR

# Script
/backup/run.sh

Timeout

# Job nach 1 Stunde abbrechen
0 3 * * * timeout 3600 /long-running-script.sh

Priorisierung

# Mit nice (niedrige Priorität)
0 3 * * * nice -n 19 /backup.sh

# Mit ionice (I/O Priorität)
0 3 * * * ionice -c3 nice -n 19 /backup.sh

Systemd Timer (Alternative)

Timer-Unit

# /etc/systemd/system/backup.timer

[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target

Service-Unit

# /etc/systemd/system/backup.service

[Unit]
Description=Backup Service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
User=root

Aktivieren

systemctl daemon-reload
systemctl enable backup.timer
systemctl start backup.timer

# Status
systemctl list-timers
systemctl status backup.timer

Vorteile von Systemd Timern

FeatureCronSystemd Timer
LoggingManuellJournald integriert
DependenciesNeinJa
Randomized DelayNeinJa
PersistentNeinJa (nachholen)
Resource LimitsNeinJa

Troubleshooting

Cron läuft nicht

# Service prüfen
systemctl status cron

# Logs prüfen
grep CRON /var/log/syslog
journalctl -u cron

# Berechtigungen
ls -la /usr/local/bin/script.sh

Script funktioniert manuell aber nicht in Cron

# 1. Vollständige Pfade verwenden
/usr/bin/php /var/www/script.php

# 2. PATH setzen
PATH=/usr/local/bin:/usr/bin:/bin

# 3. Arbeitsverzeichnis
cd /var/www && ./script.sh

# 4. Umgebung laden
source /etc/profile && /script.sh

Debug-Modus

# Test-Job
* * * * * env > /tmp/cron-env.txt 2>&1

# Prüfen
cat /tmp/cron-env.txt

Zusammenfassung

SyntaxBeispielBedeutung
*Jede Minute
0 0 Jede Stunde
0 3 *0 3 *Täglich 3:00
0 3 00 3 0Sonntags 3:00
/5 */5 *Alle 5 Min
BefehlFunktion
crontab -eBearbeiten
crontab -lAnzeigen
crontab -rLöschen
VerzeichnisAusführung
/etc/cron.hourlyStündlich
/etc/cron.dailyTäglich
/etc/cron.weeklyWöchentlich
/etc/cron.monthlyMonatlich

Fazit

Cron ist unverzichtbar für automatisierte Serveraufgaben. Die einfache Syntax ermöglicht präzise Zeitplanung. Logging und Fehlerbehandlung sollten immer implementiert werden. File-Locking verhindert parallele Ausführungen. Für komplexere Anforderungen bieten Systemd Timer zusätzliche Features wie Dependencies und integriertes Logging.