Cron Jobs and Task Automation
In this lesson, we'll explore how to automate repetitive tasks on your Ubuntu system using cron jobs. Building on your knowledge of shell scripting and system services, you'll learn to schedule tasks to run automatically at specified times, making your system administration more efficient and reliable.
Learning Goals:
- Understand what cron is and how it works
- Learn to create and manage user cron jobs
- Master cron time syntax and scheduling patterns
- Explore system-wide cron jobs and directories
- Monitor and troubleshoot cron job execution
What is Cron?
Cron is a time-based job scheduler in Unix-like operating systems. It enables users to schedule jobs (commands or scripts) to run periodically at fixed times, dates, or intervals. The cron service runs continuously in the background and checks every minute if any scheduled jobs need to be executed.
The cron system consists of:
- cron daemon: The background service that runs scheduled jobs
- crontab files: Configuration files that specify when and what to run
- cron directories: System directories for scripts that run periodically
Basic Crontab Usage
Each user can have their own crontab file. Let's start with the basic commands to manage your personal cron jobs.
crontab -l
crontab -e
crontab -r
When you run crontab -e for the first time, you'll be prompted to choose an editor. Select your preferred editor (nano is often the easiest for beginners) and this choice will be remembered for future sessions.
Understanding Cron Time Syntax
The cron time format consists of five fields followed by the command to execute:
* * * * * command_to_execute
│ │ │ │ │
│ │ │ │ └── Day of week (0-7, where 0 and 7 = Sunday)
│ │ │ └──── Month (1-12)
│ │ └────── Day of month (1-31)
│ └──────── Hour (0-23)
└────────── Minute (0-59)
Common Scheduling Patterns
# Run every minute
* * * * * /path/to/command
# Run every day at 2:30 AM
30 2 * * * /path/to/command
# Run every Monday at 9:00 AM
0 9 * * 1 /path/to/command
# Run on the 1st of every month at 6:00 AM
0 6 1 * * /path/to/command
# Run every 15 minutes
*/15 * * * * /path/to/command
# Run every weekday (Monday-Friday) at 5:00 PM
0 17 * * 1-5 /path/to/command
Practical Cron Job Examples
Let's create some practical cron jobs that you might use in real system administration scenarios.
Example 1: Automated System Updates
# Open crontab for editing
crontab -e
# Add this line to update packages every Sunday at 3:00 AM
0 3 * * 0 sudo apt update && sudo apt upgrade -y
Example 2: Regular Backup Script
First, create a simple backup script:
#!/bin/bash
# Simple home directory backup
BACKUP_DIR="/home/$(whoami)/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
tar -czf "$BACKUP_DIR/backup_$TIMESTAMP.tar.gz" /home/$(whoami)/Documents
echo "Backup completed: backup_$TIMESTAMP.tar.gz"
Make it executable and schedule it:
chmod +x /home/$(whoami)/scripts/backup_home.sh
# Add to crontab to run daily at 2:00 AM
0 2 * * * /home/$(whoami)/scripts/backup_home.sh
Example 3: Log File Cleanup
# Clean up old log files every Sunday at 4:00 AM
0 4 * * 0 find /var/log -name "*.log" -type f -mtime +30 -exec rm -f {} \;
System-wide Cron Jobs
System-wide cron jobs are stored in /etc/cron.*/ directories and can be managed by administrators.
ls /etc/cron.*
The main system cron directories are:
/etc/cron.hourly/- Scripts that run every hour/etc/cron.daily/- Scripts that run every day/etc/cron.weekly/- Scripts that run every week/etc/cron.monthly/- Scripts that run every month
System-wide cron jobs run as root by default. Be extremely careful when adding scripts to system cron directories, as they have full system access. Always test scripts thoroughly before scheduling them system-wide.
Monitoring Cron Job Execution
It's important to verify that your cron jobs are running correctly. Here are some ways to monitor them:
sudo systemctl status cron
sudo grep CRON /var/log/syslog
sudo tail -f /var/log/syslog | grep CRON
Advanced Cron Features
Environment Variables in Cron
Cron jobs run with a minimal environment. You may need to set environment variables explicitly:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOME=/home/$(whoami)
# Now your cron job with proper environment
0 3 * * * /home/$(whoami)/scripts/daily_task.sh >> /home/$(whoami)/cron.log 2>&1
Output Handling
By default, cron sends output via email. To capture output in files:
# Redirect both stdout and stderr to a log file
0 2 * * * /path/to/script.sh > /var/log/myscript.log 2>&1
# Append to log file instead of overwriting
0 2 * * * /path/to/script.sh >> /var/log/myscript.log 2>&1
# Discard output completely
0 2 * * * /path/to/script.sh > /dev/null 2>&1
Common Pitfalls
- PATH issues: Cron jobs run with a minimal PATH. Always use full paths to commands or set PATH explicitly
- Permission problems: Ensure scripts are executable and users have appropriate permissions
- Environment differences: Cron jobs don't load your shell profile. Set needed environment variables in the crontab
- Time zone confusion: Cron uses the system timezone. Verify your system's timezone settings
- Overlapping executions: Be careful with frequent jobs that might take longer to run than their interval
- No error reporting: Always implement logging to catch and diagnose failures
Summary
Cron is a powerful tool for automating repetitive tasks on your Ubuntu system. You've learned how to create and manage user cron jobs using crontab, understand the cron time syntax, create practical automation examples, work with system-wide cron directories, and monitor job execution. Remember to always test your cron jobs thoroughly and implement proper logging to ensure they run as expected.
Quiz
Show quiz
-
What command would you use to edit your personal cron jobs?
- A)
sudo crontab -e - B)
crontab -l - C)
crontab -e - D)
edit crontab
- A)
-
Which cron expression would run a job every day at 3:30 PM?
- A)
30 15 * * * - B)
15 30 * * * - C)
30 3 * * * - D)
* 15 30 * *
- A)
-
Where would you place a script that should run every hour system-wide?
- A)
/etc/cron.hourly/ - B)
/var/spool/cron/ - C)
~/.cron/ - D)
/usr/local/cron/
- A)
-
Why might a cron job fail even though the command works when run manually?
- A) Different environment variables
- B) Permission issues
- C) PATH differences
- D) All of the above
-
How can you view cron-related entries in the system log?
- A)
sudo grep CRON /var/log/syslog - B)
crontab -l - C)
systemctl status cron - D)
ps aux | grep cron
- A)
Answers:
- C -
crontab -eedits your personal cron jobs - A -
30 15 * * *means minute 30, hour 15 (3 PM), any day, any month, any day of week - A -
/etc/cron.hourly/is for system-wide hourly scripts - D - All of these are common reasons cron jobs fail
- A -
sudo grep CRON /var/log/syslogshows cron entries in the system log