How to Schedule Script with Cron
Quick Answer: Schedule Script with Cron
To schedule a script, edit your crontab with crontab -e and add a line like: 0 9 * * * /path/to/script.sh. This runs the script daily at 9:00 AM. The five fields are: minute, hour, day of month, month, day of week. Use * for βanyβ and comma-separated lists for multiple values.
Quick Comparison: Scheduling Methods
| Frequency | Cron Expression | Best For | Complexity |
|---|---|---|---|
| Every minute | * * * * * | Frequent tasks | Simple |
| Hourly | 0 * * * * | Regular checks | Simple |
| Daily | 0 9 * * * | Daily jobs | Simple |
| Weekly | 0 9 * * 0 | Weekly tasks | Simple |
| Complex | Multiple entries | Many schedules | Moderate |
Bottom line: Use crontab -e to edit; use simple expressions for common schedules.
Schedule Bash scripts to run periodically using cron. Learn cron syntax, crontab management, and practical scheduling examples.
Cron Syntax
Cron uses five fields to define scheduling:
ββββββββββββββ minute (0 - 59)
β ββββββββββββββ hour (0 - 23)
β β ββββββββββββββ day of month (1 - 31)
β β β ββββββββββββββ month (1 - 12)
β β β β ββββββββββββββ day of week (0 - 7) (0 or 7 is Sunday)
β β β β β
β β β β β
* * * * * command_to_run
Basic Examples
# Run every day at 2:30 AM
30 2 * * * /path/to/script.sh
# Run every hour
0 * * * * /path/to/script.sh
# Run every 15 minutes
*/15 * * * * /path/to/script.sh
# Run at 9:00 AM on weekdays
0 9 * * 1-5 /path/to/script.sh
# Run at midnight
0 0 * * * /path/to/script.sh
Edit Crontab
# Edit your crontab
crontab -e
# List current cron jobs
crontab -l
# Remove all cron jobs
crontab -r
# Edit another user's crontab (as root)
crontab -u username -e
Cron Fields Explained
| Field | Range | Example |
|---|---|---|
| Minute | 0-59 | 30 = 30 minutes |
| Hour | 0-23 | 14 = 2 PM |
| Day | 1-31 | 15 = 15th of month |
| Month | 1-12 | 3 = March |
| Day of Week | 0-7 | 5 = Friday (0,7 = Sunday) |
Special Characters
* # Any value
, # Multiple values (1,3,5)
- # Range (1-5)
/ # Step value (*/5 = every 5)
Practical Example: Daily Backup
#!/bin/bash
# File: daily_backup.sh
backup_dir="/backups"
source_dir="/home/user/documents"
date=$(date +%Y%m%d)
mkdir -p "$backup_dir"
# Create backup
tar -czf "$backup_dir/documents_$date.tar.gz" "$source_dir"
# Keep only last 7 backups
find "$backup_dir" -name "documents_*.tar.gz" -mtime +7 -delete
echo "Backup completed: documents_$date.tar.gz"
Add to crontab:
# Run daily at 3:00 AM
0 3 * * * /path/to/daily_backup.sh
$ crontab -e
# Add the line above, save, and exit
Practical Example: Log Cleanup
#!/bin/bash
# File: cleanup_logs.sh
log_dir="/var/log/myapp"
keep_days=30
if [ ! -d "$log_dir" ]; then
echo "ERROR: Directory not found: $log_dir"
exit 1
fi
# Remove logs older than 30 days
find "$log_dir" -name "*.log" -mtime +$keep_days -delete
# Count remaining logs
count=$(find "$log_dir" -name "*.log" | wc -l)
echo "Cleanup completed: $count logs remaining"
Add to crontab:
# Run daily at 4:00 AM
0 4 * * * /path/to/cleanup_logs.sh
Common Cron Expressions
# Every minute
* * * * * /path/to/script.sh
# Every 5 minutes
*/5 * * * * /path/to/script.sh
# Every hour
0 * * * * /path/to/script.sh
# Every day at 6 AM
0 6 * * * /path/to/script.sh
# Every Monday at 9 AM
0 9 * * 1 /path/to/script.sh
# First day of month at 8 AM
0 8 1 * * /path/to/script.sh
# Every quarter (Jan, Apr, Jul, Oct)
0 0 1 1,4,7,10 * /path/to/script.sh
# Every weekday at 5 PM
0 17 * * 1-5 /path/to/script.sh
# Twice daily (6 AM and 6 PM)
0 6,18 * * * /path/to/script.sh
Cron with Output Redirection
# Run at 2 AM, save output to log file
0 2 * * * /path/to/script.sh >> /var/log/script.log 2>&1
# Run and email output
0 3 * * * /path/to/script.sh | mail -s "Backup Report" admin@example.com
# Append with timestamp
0 4 * * * echo "Running at $(date)" >> /tmp/cron.log && /path/to/script.sh >> /tmp/cron.log 2>&1
Monitor Cron Jobs
# Check if cron is running
systemctl status cron
# View system cron log
sudo tail -f /var/log/syslog | grep CRON
# Check cron execution history
sudo grep CRON /var/log/syslog
Practical Example: Monitoring Script
#!/bin/bash
# File: monitor_service.sh
service_name="myapp"
log_file="/var/log/service_monitor.log"
email="admin@example.com"
# Check if service is running
if ! systemctl is-active --quiet "$service_name"; then
message="ERROR: $service_name is down!"
echo "$(date): $message" >> "$log_file"
# Send alert
echo "$message" | mail -s "Service Alert" "$email"
# Attempt restart
systemctl restart "$service_name"
fi
Add to crontab:
# Check every 5 minutes
*/5 * * * * /path/to/monitor_service.sh
Practical Example: Hourly Report
#!/bin/bash
# File: hourly_report.sh
report_file="/tmp/hourly_report_$(date +%Y%m%d_%H).txt"
{
echo "=== Hourly System Report ==="
echo "Time: $(date)"
echo ""
echo "=== Disk Usage ==="
df -h /
echo ""
echo "=== Memory Usage ==="
free -h
echo ""
echo "=== Top Processes ==="
ps aux | sort -rk 3,3 | head -5
} > "$report_file"
echo "Report saved: $report_file"
Add to crontab:
# Run every hour
0 * * * * /path/to/hourly_report.sh
Environment Variables in Cron
# Set environment variables before cron command
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
MAILTO=admin@example.com
# Then add your cron jobs
0 2 * * * /path/to/script.sh
Debugging Cron Issues
#!/bin/bash
# Script with debugging output
LOG="/tmp/cron_debug_$(date +%s).log"
{
echo "Starting at: $(date)"
echo "User: $(whoami)"
echo "Current dir: $(pwd)"
echo "PATH: $PATH"
# Your commands here
/path/to/script.sh
echo "Ended at: $(date)"
} >> "$LOG" 2>&1
Crontab for Specific Users
# View root's crontab
sudo crontab -u root -l
# Edit another user's crontab
sudo crontab -u username -e
# System-wide crontab
sudo vi /etc/crontab
Common Mistakes
- Not using full paths - cron doesnβt have PATH set like interactive shell
- Forgetting to make script executable -
chmod +x script.sh - Wrong time format - use
0-59for minutes,0-23for hours - MAILTO not set - cron wonβt send emails silently
- Scripts creating files - need proper permissions in cron context
Performance Tips
- Avoid running too many jobs at once
- Schedule heavy jobs during off-hours
- Use
flockto prevent concurrent runs - Redirect output to prevent email floods
- Test script manually before scheduling
Key Points
- Five fields: minute, hour, day, month, day_of_week
- Use full paths in cron jobs
- Redirect output to log files
- Test scripts before adding to crontab
- Check syslog for cron execution errors
Summary
Cron is powerful for scheduling automated tasks. Always use full paths, test scripts first, and monitor execution. Proper logging helps debug issues. Remember that cron environment is minimal compared to interactive shell.