DEV Community

Nagesh K
Nagesh K

Posted on

πŸ”₯ Automating Linux Tasks: Cron Jobs + Logging

Automation is the backbone of DevOps, and cron jobs are one of the simplest yet most powerful tools for scheduling repetitive tasks in Linux. But here’s the golden rule : Never run cron without logs.
Without logs, you’re flying blind β€” you won’t know if your job succeeded, failed, or silently broke.

πŸ•’ What is a Cron Job?
Cron is a time-based job scheduler in Unix/Linux.
It runs commands or scripts at specified intervals (minutes, hours, days).
Perfect for tasks like backups, monitoring, cleanup, or reporting.

βœ… Example: Disk Usage Monitoring with Logging
Here’s a production-ready cron job:

*/5 * * * * /home/ubuntu/disk.sh >> /home/ubuntu/disk.log 2>&1
*/5 * * * * β†’ Run every 5 minutes
Enter fullscreen mode Exit fullscreen mode

/home/ubuntu/disk.sh β†’ Script to check disk usage
>> /home/ubuntu/disk.log β†’ Append standard output to log file
2>&1 β†’ Redirect errors to the same log file
πŸ‘‰ This ensures both success and failure messages are captured.

πŸ›‘οΈ Why Logging Matters
Observability β†’ Know what happened at each run.
Debugging β†’ Errors are visible in logs.
Auditing β†’ Historical record of job execution.
Reliability β†’ Prevents silent failures.

⚑ Common Mistake: Typo in Service Name
A real-world example you might encounter:
ubuntu@ip-172-31-39-174:~/shell-script-learnings$ sudo systemctl stop corn
Failed to stop corn.service: Unit corn.service not loaded.

πŸ‘‰ The error happened because the service name is cron, not corn.
Correct command:

sudo systemctl stop cron
sudo systemctl start cron
sudo systemctl status cron
Enter fullscreen mode Exit fullscreen mode

πŸ“ Managing Cron Jobs

1. Add a Cron Job
crontab -e : Paste your job line, save, and exit.

2. List Current Cron Jobs
crontab -l

3. Remove a Specific Cron Job
Open crontab: crontab -e
Delete the line corresponding to the job, Save and exit.

4. Delete All Cron Jobs
crontab -r
⚠️ This wipes the entire crontab for the user.

πŸš€ Production Enhancements

Timestamps in logs:
*/5 * * * * echo "$(date) - Running disk.sh" >> /home/ubuntu/disk.log 2>&1; /home/ubuntu/disk.sh >> /home/ubuntu/disk.log 2>&1
Log rotation (prevent infinite growth):
Create /etc/logrotate.d/disk:
Code:

/home/ubuntu/disk.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 644 ubuntu ubuntu
}
Enter fullscreen mode Exit fullscreen mode

🎯 Conclusion
Cron jobs are deceptively simple but incredibly powerful. The difference between a hobby script and a production-grade job is logging and management.
Always log output and errors.
Monitor logs with rotation.
Manage jobs cleanly with crontab -e, crontab -l, and crontab -r.

Top comments (0)