Day 18 – Automating Tasks with Cron Jobs

🛠️ Day 18 of my DevOps journey introduced me to the power of cron jobs – the classic way to automate repetitive tasks in Linux. Today I scheduled log backups, tested simple echo jobs, and experimented with different cron timing formats.


⏰ What is cron?

cron is a time-based job scheduler in Unix-like systems that allows you to run scripts or commands at scheduled times or intervals.

📁 Backup Jenkins Logs Every Day

🔄 Backup Script

#!/bin/bash
tar -czf /opt/jenkins_logs_$(date +\%F).tar.gz /var/log/jenkins/

Let’s say we save this as /opt/backup_jenkins.sh and make it executable:

chmod +x /opt/backup_jenkins.sh

🗓️ Set Up a Cron Job

Edit the crontab:

crontab -e

Add this line to run the script daily at 2:00 AM:

0 2 * * * /opt/backup_jenkins.sh

✅ This runs:

  • Minute = 0

  • Hour = 2

  • Every Day, Every Month, Every Weekday


📌 Sample Cron Timings

ExpressionDescription
*/5 * * * *Every 5 minutes
0 * * * *Every hour
0 0 * * *Every day at midnight
0 0 * * 0Every Sunday at midnight
0 8-18 * * 1-5Hourly from 8am–6pm, Mon–Fri

👨‍🔬 Test Cron with Simple Commands

Echo a message to a file every minute:

* * * * * echo "Hello from Cron at $(date)" >> /tmp/cron_test.log

Verify it with:

tail -f /tmp/cron_test.log

🧠 What I Learned

✅ Automate tasks with crontab
✅ Time format: min hour day month weekday
✅ Use absolute paths in scripts
✅ Output redirection helps debug cron failures


🛠️ Real-World Use Cases

  • Log and config backups

  • Auto-restarts of services

  • Pull updates from Git

  • Rotate or clean logs

  • Monitoring scripts


🔮 Next Steps

On Day 19, I’ll move on to exploring rsync for syncing files across servers and learning about SSH key-based authentication.

0
Subscribe to my newsletter

Read articles from Shaharyar Shakir directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shaharyar Shakir
Shaharyar Shakir