Shell Scripting: Scheduling Tasks with Cron Jobs
What is a Cron Job?
✅ A cron job is a scheduled task that runs automatically at specific intervals.
✅ Cron is the time-based job scheduler built into Unix/Linux systems.
✅ You set a schedule + set a command → Cron executes it automatically, even if you forget.
🛠️ How Cron Syntax Works (5-Star Format ⭐⭐⭐⭐⭐)
Every cron job uses 5 stars:
* * * * * command_to_run
| | | | |
| | | | └─ Day of Week (0-7) (0 = Sunday)
| | | └──── Month (1-12)
| | └─────── Day of Month (1-31)
| └────────── Hour (0-23)
└───────────── Minute (0-59)
✅ Each star can be:
📚 Example Cron Jobs
✅ Every minute:
* * * * * /path/to/script.sh
✅ Every day at midnight:
0 0 * * * /path/to/daily_backup.sh
✅ Every Monday at 5 AM:
0 5 * * 1 /path/to/weekly_report.sh
✅ Every 15 minutes:
*/15 * * * * /path/to/ping_server.sh
✅ Cron is flexible — you can automate anything:
🛠️ How to Set Up a Cron Job
✅ 1. Edit your crontab:
crontab -e
✅ 2. Add a new line in the crontab:
*/10 * * * * /home/ubuntu/scripts/monitor_disk_usage.sh
✅ 3. Save and exit.
✅ 4. View your cron jobs:
crontab -l
✅ 5. Remove your cron jobs:
crontab -r
🛠️ Important Tip: Redirect Output!
✅ Always redirect stdout/stderr:
* * * * * /path/to/script.sh > /tmp/script.log 2>&1
✅ Otherwise, cron will flood your email or hide your script errors silently!
✅ 2>&1 = redirect errors to the same file as standard output.
📚 Real Observability Examples with Cron
✅ Monitor CPU load every 5 minutes:
*/5 * * * * /home/ubuntu/scripts/check_cpu.sh > /tmp/cpu.log 2>&1
✅ Clear old logs every night at 1 AM:
0 1 * * * /home/ubuntu/scripts/clear_old_logs.sh > /tmp/clear.log 2>&1
✅ Ping critical servers every minute:
* * * * * /home/ubuntu/scripts/ping_critical_servers.sh > /tmp/ping.log 2>&1
✅ Cron + Shell = Lightweight, Reliable Observability Stack
🧠 Simple Analogy
Setting up a cron job is like training a loyal watchdog 🐕:
Smart cron usage = stable automation.
🗺️ Where Are We in the Journey?
Linux Fundamentals → Kubernetes Observability → Shell Basics → Conditions → Loops → Functions → Error Handling → Background Jobs → Now: Scheduled Cron Automation
✅ You’re now building self-sustaining observability systems!