Problem Statement
Explain advanced cron usage including environment variables, output handling, error reporting, and alternatives like systemd timers.
Explanation
Cron environment: limited PATH, HOME=/home/user, SHELL=/bin/sh by default. Set variables in crontab: PATH=/usr/local/bin:/usr/bin:/bin, MAILTO=admin@example.com, SHELL=/bin/bash. Variables before entries apply to all subsequent entries. Example:
```
PATH=/usr/local/bin:/bin:/usr/bin
MAILTO=admin@example.com
0 2 * * * /path/to/backup.sh
```
Output handling: cron emails stdout/stderr to MAILTO user (if mail configured). Redirect: 0 2 * * * /path/to/script.sh > /var/log/backup.log 2>&1 logs output. Suppress: 0 2 * * * /path/to/script.sh > /dev/null 2>&1 discards all output. Email only errors: 0 2 * * * /path/to/script.sh > /var/log/backup.log sends only stderr via email.
Error reporting: wrap scripts with error handling:
```bash
#!/bin/bash
set -e
trap 'echo "Backup failed" | mail -s "Backup Error" admin@example.com' ERR
# Backup commands
```
Or use cron wrapper: 0 2 * * * /usr/local/bin/cron-wrapper /path/to/script.sh where wrapper handles logging and error notification.
Locking: prevent overlapping executions:
```bash
0 */6 * * * flock -n /var/lock/backup.lock -c '/path/to/backup.sh'
```
Flock ensures only one instance runs. Alternative: check for PID file in script.
Systemd timers: modern alternative to cron. Create timer unit (/etc/systemd/system/backup.timer):
```
[Unit]
Description=Backup Timer
[Timer]
OnCalendar=daily
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
```
And service unit (backup.service). Enable: systemctl enable backup.timer, systemctl start backup.timer.
Advantages of timers: better logging with journalctl, dependency handling, RandomizedDelaySec for load distribution, OnBootSec for run-after-boot. List: systemctl list-timers. Disadvantages: more complex setup, systemd-specific.
At command: one-time scheduled tasks. at 10pm runs commands entered interactively. at 2:30 AM tomorrow < script.sh schedules script. List: atq, remove: atrm jobnumber. Understanding scheduling options enables reliable task automation.