Scheduling & Automation
Scheduling & Automation
6 interactive questions
Cron vs systemd timers — when to use which?
cron — simple, user-level, ubiquitous, crontab -e. systemd timers — system-level, logging/journal, dependencies, accuracy, RandomizedDelaySec=, Persistent= (run if missed). Use timers for services; cron for user scripts.
Crontab syntax and common pitfalls?
* * * * * command (min hour dom mon dow). Pitfalls: % needs escaping, environment differs from shell (set PATH, HOME, SHELL), stdout/stderr go to mail (redirect: > /dev/null 2>&1), overlapping runs (use flock or systemd).
How do you run a job only once at a specific time?
at 14:30 (interactive) or echo "cmd" | at 14:30. atq lists, atrm N removes. batch runs when load < 1.5.
What is anacron and when is it useful?
Runs jobs periodically even if the system was off at the scheduled time. Reads /etc/anacrontab (period in days, delay in minutes, identifier, command). Good for laptops/desktops that aren't always on.
How do you prevent overlapping cron jobs?
Use flock -n /tmp/mylock.lock -c "command" (exits if locked). Or systemd timer with LockPersonality=/LockNamespace=. For scripts: implement PID file locking manually.
How do you schedule a job to run on the first Monday of the month?
Cron can't do "first Monday" directly. Two approaches: 1) 0 0 1-7 * 1 cmd (runs 1st-7th, then filter in script: [[ $(date +\%d) -le 7 ]]). 2) Use systemd timer with OnCalendar=Mon *-*-1..7.