_____                   _             ___     _________  __
 |_   _|__ _ __ _ __ ___ (_)_ __   __ _| \ \   / / ____\ \/ /
   | |/ _ \ '__| '_ ` _ \| | '_ \ / _` | |\ \ / /|  _|  \  /
   | |  __/ |  | | | | | | | | | | (_| | | \ V / | |___ /  \
   |_|\___|_|  |_| |_| |_|_|_| |_|\__,_|_|  \_/  |_____/_/\_\
advanced13 min

Task Automation with Cron Jobs

What is Cron?

Cron is a time-based job scheduling service in Unix and Linux operating systems. Its name derives from the Greek word "chronos," meaning "time." It runs in the background as a daemon and automatically executes commands or scripts at intervals you specify. From server administration to data backup, log cleanup to system monitoring, many critical tasks are automated with cron.

The cron service starts automatically when the system boots and checks crontab files every minute to trigger tasks whose scheduled time has arrived. This allows system administrators and developers to avoid performing repetitive tasks manually. From a backup script that runs once a day to a monitoring command that runs every five minutes, any scheduling is possible with cron.

Crontab Syntax

Cron jobs are defined in crontab (cron table) files. Each line represents a task and consists of five time fields followed by the command to execute. These five fields are, in order: minute, hour, day of month, month, and day of week.

# Crontab syntax
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of week (0 - 7, 0 and 7 = Sunday)
# │ │ │ │ │
# * * * * * command

Special Characters

  • * (Asterisk): Means every value. For example, * in the minute field means every minute.
  • , (Comma): Used to specify multiple values. For example, 1,15,30 means the 1st, 15th, and 30th minutes.
  • - (Hyphen): Specifies a range. 9-17 means every hour from 9 to 17.
  • / (Slash): Specifies a step value. */5 means every 5 units.

Crontab Management

Crontab Commands

# Edit your crontab file
$ crontab -e

# List your current crontab entries
$ crontab -l

# Remove your crontab file (use with caution!)
$ crontab -r

# Edit another user's crontab (requires root)
$ sudo crontab -u username -e

# List another user's crontab
$ sudo crontab -u username -l

Common Scheduling Examples

# Run every day at midnight
0 0 * * * /home/user/scripts/backup.sh

# Run every hour
0 * * * * /usr/local/bin/check.sh

# Run every 5 minutes
*/5 * * * * /home/user/monitor.sh

# Run every Monday at 08:00 AM
0 8 * * 1 /home/user/weekly-report.sh

# Run on the 1st of every month at 02:00 AM
0 2 1 * * /home/user/monthly-cleanup.sh

# Run every weekday (Mon-Fri) every hour from 9 AM to 5 PM
0 9-17 * * 1-5 /home/user/business-hours-check.sh

# Run twice a year: Jan 1 and Jul 1 at midnight
0 0 1 1,7 * /home/user/semi-annual.sh

Special Time Shortcuts

# Run once at startup
@reboot /home/user/startup.sh

# Run once a day at midnight (same as 0 0 * * *)
@daily /home/user/daily.sh

# Run once an hour (same as 0 * * * *)
@hourly /home/user/hourly.sh

# Run once a week (same as 0 0 * * 0)
@weekly /home/user/weekly.sh

# Run once a month (same as 0 0 1 * *)
@monthly /home/user/monthly.sh

Practical Examples

Automated Backup Script

#!/bin/bash
# backup.sh - Database and file backup
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/home/user/backups"

# MySQL database backup
mysqldump -u root -p'password' database > "$BACKUP_DIR/db_$DATE.sql"

# Compress and backup project files
tar -czf "$BACKUP_DIR/files_$DATE.tar.gz" /var/www/html/

# Delete backups older than 30 days
find "$BACKUP_DIR" -name "*.sql" -mtime +30 -delete
find "$BACKUP_DIR" -name "*.tar.gz" -mtime +30 -delete

echo "Backup completed: $DATE" >> /var/log/backup.log
# Add to crontab: Backup every night at 03:00
0 3 * * * /home/user/scripts/backup.sh

Log Rotation

#!/bin/bash
# log-rotate.sh - Rotate application logs
LOG_DIR="/var/log/myapp"
DATE=$(date +%Y%m%d)

# Rename the current log
mv "$LOG_DIR/app.log" "$LOG_DIR/app_$DATE.log"

# Compress the old log
gzip "$LOG_DIR/app_$DATE.log"

# Delete logs older than 90 days
find "$LOG_DIR" -name "*.gz" -mtime +90 -delete

# Notify the application to reopen logs
kill -HUP $(cat /var/run/myapp.pid)

System Monitoring

#!/bin/bash
# monitor.sh - Disk and memory check
THRESHOLD=90

# Check disk usage
DISK_USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt "$THRESHOLD" ]; then
    echo "WARNING: Disk usage is ${DISK_USAGE}%" | mail -s "Disk Alert" admin@example.com
fi

# Check memory usage
MEM_USAGE=$(free | grep Mem | awk '{printf "%.0f", $3/$2 * 100}')
if [ "$MEM_USAGE" -gt "$THRESHOLD" ]; then
    echo "WARNING: Memory usage is ${MEM_USAGE}%" | mail -s "Memory Alert" admin@example.com
fi

Environment Variables in Cron

Cron jobs run in a minimal environment that differs from your user session. Environment variables you use in your scripts may not be defined in the cron environment. To solve this, you can define required variables at the top of your crontab file or use absolute paths in your scripts.

# Define environment variables in crontab
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MAILTO=admin@example.com
HOME=/home/user

# Now define your jobs
0 3 * * * /home/user/scripts/backup.sh
*/5 * * * * /home/user/scripts/monitor.sh

Troubleshooting Cron

Checking Cron Logs

# View cron logs (Debian/Ubuntu)
$ grep CRON /var/log/syslog

# Cron log on CentOS/RHEL
$ cat /var/log/cron

# Check the cron service status
$ systemctl status cron

# Redirect output to a file (for debugging)
*/5 * * * * /home/user/script.sh >> /tmp/cron-output.log 2>&1

Common Issues

  • PATH issue: Cron uses a minimal PATH. Use full paths for commands or define PATH in your crontab.
  • Permission issue: Ensure the script has execute permission: chmod +x script.sh
  • Output issue: Cron sends output via email by default. Disable with MAILTO="".
  • Newline issue: The crontab file must end with a blank line.
  • Relative path issue: Always use absolute paths.

Summary

Cron is one of the cornerstones of Linux system administration. Regular backups, log management, system monitoring, and maintenance tasks can be reliably automated with cron. Learning crontab syntax, understanding how the five time fields work, and resolving environment variable issues are the keys to building an efficient automation infrastructure. When you schedule your tasks with cron, you save time and minimize the risk of human error.