Chapter 2 · Lesson 5
Intermediate
1 min read
Cron and Scheduled Tasks
Overview
Cron starts commands at scheduled times. It has no interactive terminal, a limited environment and may run as a specific user. Scheduled scripts need absolute paths, explicit environment variables and output logging.
Detailed Notes
View a crontab
bash
crontab -l
crontab -e
Each user has a separate crontab. An entry has five time fields and a command:
text
minute hour day-of-month month day-of-week command
Example:
text
15 2 * * * /usr/local/bin/backup-db.sh >> /var/log/backup-db.log 2>&1
This means every day at 02:15.
Common fields:
| Field | Range |
|---|---|
| Minute | 0-59 |
| Hour | 0-23 |
| Day | 1-31 |
| Month | 1-12 |
| Weekday | 0-7, where 0 and 7 can mean Sunday |
Make the script reliable
bash
#!/usr/bin/env bash
set -euo pipefail
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
exec /opt/app/backup.sh
- Use absolute paths.
- Set
PATH. - Redirect stdout and stderr.
- Avoid interactive prompts.
- Lock concurrent runs if two instances can overlap.
systemd timers
Modern systems often replace cron with systemd timers. A timer schedules a service and can retain logs and restart behavior in the service manager.
Common Interview Questions
Finished this lesson?
0 of 25 lessons done · 0% of the course

