Cron, at, and Scheduled Tasks
Chapter 20: Cron, at, and Scheduled Tasks
Section titled “Chapter 20: Cron, at, and Scheduled Tasks”Overview
Section titled “Overview”This chapter covers scheduled task management in Linux using cron, at, and systemd timers.
Why This Matters in DevOps/SRE
Section titled “Why This Matters in DevOps/SRE”Scheduled tasks are essential for automation and maintenance:
Scheduled Tasks for DevOps/SRE+------------------------------------------------------------------+| || Automation & Operations: || +----------------------------------------------------------+ || | Log rotation → Daily/weekly log cleanup | || | Backups → Scheduled database/file backups | || | Health checks → Periodic service monitoring | || | Certificate renewal → Let's Encrypt automation | || +----------------------------------------------------------+ || || CI/CD Pipelines: || +----------------------------------------------------------+ || | Nightly builds → Scheduled pipeline runs | || | Testing → Periodic security scans | || | Deployments → Scheduled rollout windows | || +----------------------------------------------------------+ || || Kubernetes: || +----------------------------------------------------------+ || | CronJobs → Scheduled pod execution | || | CronJob controller → Manages scheduled jobs | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Practical Impact:
- Automate repetitive maintenance tasks
- Schedule backups and log rotation
- Run periodic health checks and monitoring
- Trigger CI/CD pipelines
20.1 Cron System
Section titled “20.1 Cron System”Cron Basics
Section titled “Cron Basics” Cron System Architecture+------------------------------------------------------------------+| || +---------------+ +---------------+ +---------------+ || | crontab | | cron | | /etc/cron.d | || | files |---->| daemon |---->| scripts | || +---------------+ +---------------+ +---------------+ || | | | || v v v || +---------------+ +---------------+ +---------------+ || | User crontabs| | cron jobs | | System cron | || | /var/spool/ | | execution | | jobs | || +---------------+ +---------------+ +---------------+ || |+------------------------------------------------------------------+Cron Syntax
Section titled “Cron Syntax”# ┌───────────── minute (0 - 59)# │ ┌───────────── hour (0 - 23)# │ │ ┌───────────── day of month (1 - 31)# │ │ │ ┌───────────── month (1 - 12)# │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday=0)# │ │ │ │ │# * * * * * command
# Examples:0 5 * * * # Run at 5:00 AM daily0 0 * * 0 # Run at midnight on Sundays30 4 1,15 * * # Run at 4:30 AM on 1st and 15th0 8 * * 1-5 # Run at 8 AM on weekdays*/15 * * * * # Run every 15 minutes0 */2 * * * # Run every 2 hours@reboot # Run at reboot@yearly # Run once a year (0 0 1 1 *)@monthly # Run once a month (0 0 1 * *)@weekly # Run once a week (0 0 * * 0)@daily # Run once a day (0 0 * * *)@hourly # Run every hour (0 * * * *)Managing Crontabs
Section titled “Managing Crontabs”# Edit current user's crontabcrontab -e
# List current user's crontabcrontab -l
# Remove current user's crontabcrontab -r
# Edit specific user's crontab (root only)crontab -u username -e
# List specific user's crontabcrontab -u username -lSystem Crontabs
Section titled “System Crontabs”# System cron directories/etc/cron.d/ # System-wide cron jobs/etc/cron.daily/ # Scripts run daily/etc/cron.hourly/ # Scripts run hourly/etc/cron.monthly/ # Scripts run monthly/etc/cron.weekly/ # Scripts run weekly
# Example: /etc/cron.d/maintance# Run maintenance script at 2 AM daily0 2 * * * root /usr/local/bin/maintenance.sh20.2 at Command
Section titled “20.2 at Command”at Basics
Section titled “at Basics”# Install at if neededsudo pacman -S at
# Schedule a job to run at specific timeat 2:30 PMat> /path/to/command# Ctrl+D to save
# Schedule a job for specific dateat 2:30 PM + 2 daysat 14:30 2026-12-25
# List pending jobsatq# orat -l
# Remove a jobatrm job_numberat Examples
Section titled “at Examples”# Run a command in 1 hourat now + 1 hour
# Run a command tomorrow at 10 AMat 10:00 tomorrow
# Run a script at bootat now + 1 minute -f /path/to/script.sh
# View job detailsat -c job_number20.3 Systemd Timers
Section titled “20.3 Systemd Timers”Timer Units
Section titled “Timer Units”[Unit]Description=Run daily cleanup
[Timer]OnCalendar=dailyPersistent=trueRandomizedDelaySec=1h
[Install]WantedBy=timers.target[Unit]Description=Daily cleanup service
[Service]Type=oneshotExecStart=/usr/local/bin/cleanup.shTimer Commands
Section titled “Timer Commands”# Start timersudo systemctl start mytimer.timer
# Enable timer (start on boot)sudo systemctl enable mytimer.timer
# List active timerssystemctl list-timerssystemctl list-timers --all
# View timer statussystemctl status mytimer.timer
# View timer next runsystemctl list-timers --all | grep mytimerTimer Examples
Section titled “Timer Examples”# Run every hourOnCalendar=hourly# orOnCalendar=*:0/1
# Run every 30 minutesOnCalendar=*:0/30
# Run at specific time dailyOnCalendar=*-*-* 02:00:00
# Run on specific daysOnCalendar=Mon *-*-* 09:00:00
# Run weekly (Sunday at 3 AM)OnCalendar=Sun *-*-* 03:00:00
# Run monthly (1st of month at midnight)OnCalendar=*-*-01 00:00:0020.4 Anacron
Section titled “20.4 Anacron”Anacron Basics
Section titled “Anacron Basics”# Installsudo pacman -S cronie # Contains anacron
# format: delay job_identifier command1 5 cron.daily run-parts /etc/cron.daily7 25 cron.weekly run-parts /etc/cron.weekly30 60 cron.monthly run-parts /etc/cron.monthly
# Run anacron manuallysudo anacron -d20.5 Best Practices
Section titled “20.5 Best Practices”Logging and Monitoring
Section titled “Logging and Monitoring”# Redirect output to log file0 5 * * * /path/to/script.sh >> /var/log/script.log 2>&1
# Send email on failure0 5 * * * /path/to/script.sh || echo "Failed" | mail -s "Cron Failed" admin@example.comEnvironment Variables
Section titled “Environment Variables”# In crontab, set PATHPATH=/usr/local/bin:/usr/bin:/bin
# Set HOMEHOME=/root
# Set SHELLSHELL=/bin/bashCommon Pitfalls
Section titled “Common Pitfalls”# Problem: Missing PATH in cron# Solution: Define PATH at top of crontab
# Problem: Commands not found# Solution: Use full paths: /usr/bin/command
# Problem: Scripts not executing# Solution: Make script executable: chmod +x script.sh
# Problem: Environment differences# Solution: Source profile in script: source /etc/profile20.6 Advanced Scheduling
Section titled “20.6 Advanced Scheduling”systemd.time Calendar Format
Section titled “systemd.time Calendar Format”# Complex calendar expressionsOnCalendar=Mon..Fri 09:00:00 # Weekdays at 9 AMOnCalendar=*-*-1..7 18:00:00 # First week of month at 6 PMOnCalendar=*:0/15 # Every 15 minutesOnCalendar=Sat,Sun 10:00 # Weekends at 10 AM
# Combined with delaysOnBootSec=5min # 5 minutes after bootOnUnitActiveSec=1h # 1 hour after last activationOnUnitInactiveSec=30m # 30 minutes after deactivationCommon Mistakes & Anti-Patterns
Section titled “Common Mistakes & Anti-Patterns”1. Using Wrong Timezone
Section titled “1. Using Wrong Timezone”# ❌ WRONG: Not specifying timezone# Jobs run at wrong time, causing confusion0 3 * * * /scripts/backup # Is this UTC? Local?
# ✅ CORRECT: Specify timezoneCRON_TZ=America/New_York0 3 * * * /scripts/backup # Now 3 AM New York time2. Not Redirecting Output
Section titled “2. Not Redirecting Output”# ❌ WRONG: Cron output fills up* * * * * /scripts/myscript > /dev/null 2>&1# No logging, no debugging!
# ✅ CORRECT: Log output* * * * * /scripts/myscript >> /var/log/myscript.log 2>&13. Not Using systemd Timers
Section titled “3. Not Using systemd Timers”# ❌ WRONG: Still using cron for everything# cron doesn't integrate with journalctl# No dependency management
# ✅ CORRECT: Use systemd timers# Better logging, dependency management, reliable4. Missing PATH
Section titled “4. Missing PATH”# ❌ WRONG: Assuming PATH is set* * * * * myscript # Command not found!
# ✅ CORRECT: Set full PATHPATH=/usr/local/bin:/usr/bin:/bin* * * * * /opt/scripts/myscriptInterview Questions
Section titled “Interview Questions”- What is the difference between cron and systemd timers?
- How do you debug a cron job that’s not running?
- What is anacron and when would you use it?
- How do you run a job only once in the future?
- **Explain the cron syntax: * * * * ***
- What are the advantages of systemd timers over cron?
Summary
Section titled “Summary”In this chapter, you learned:
- ✅ Cron syntax and management
- ✅ at command for one-time tasks
- ✅ systemd timers for modern scheduling
- ✅ Anacron for systems not running 24/7
- ✅ Best practices and troubleshooting
Next Chapter
Section titled “Next Chapter”Chapter 21: Networking Fundamentals
Last Updated: February 2026