Scheduling: cron & systemd timers

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Automation Concepts

Scheduling: cron & systemd timers

Beginner ⭐ 50 XP ⏱ 16 min #automation#cron#systemd#scheduling

Run jobs on a schedule with cron syntax and modern systemd timers.

📖Theory

Scheduled jobs power backups, cleanups, and reports. cron is the classic scheduler. A crontab line has five time fields plus a command:

┌ minute ┌ hour ┌ day-of-month ┌ month ┌ day-of-week
*        *      *              *       *   command

systemd timers are the modern alternative: a .timer unit triggers a .service unit. They add nice features cron lacks — calendar syntax, missed-run catch-up (Persistent=true), logging via the journal, and dependencies.

🌍Real-World Example
# crontab -e
0 2 * * *      /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1   # 2am daily
*/15 * * * *   /usr/local/bin/healthcheck.sh                          # every 15 min
0 9 * * 1      /usr/local/bin/weekly-report.sh                        # Mondays 9am
# /etc/systemd/system/backup.timer
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
# enable with: systemctl enable --now backup.timer
✍️Hands-On Exercise
  1. Write a cron line that runs a script every weekday at 6:30 PM.
  2. Use crontab.guru to decode 30 3 1 * *.
  3. Redirect a cron job’s output and errors to a log file.
  4. Convert a cron schedule into a systemd timer OnCalendar= expression.
🧾Cheat Sheet
Schedulecron
Every minute* * * * *
Every 15 min*/15 * * * *
Daily 2am0 2 * * *
Mondays 9am0 9 * * 1
Edit crontabcrontab -e
List crontabcrontab -l
systemd timerOnCalendar= + systemctl enable --now x.timer
💬Common Interview Questions
What are the five fields of a cron expression?

Minute, hour, day-of-month, month, and day-of-week, followed by the command. An asterisk means “every”.

Why might a script work in your shell but fail under cron?

cron runs with a minimal environment (bare PATH, no profile). Missing absolute paths or env vars cause failures. Use full paths and set needed variables.

What advantages do systemd timers have over cron?

Calendar syntax, catch-up for missed runs (Persistent), integrated journal logging, dependencies on other units, and easier per-job resource control.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type