crontab Command

Schedule and manage automated tasks using the cron daemon for time-based job scheduling in Linux systems.

Syntax

crontab [OPTIONS] [FILE] crontab -e crontab -l crontab -r

The crontab command manages cron jobs - scheduled tasks that run automatically at specified times and intervals.

Common Options

Option Description
-e Edit the current crontab
-l List the current crontab
-r Remove the current crontab
-u USER Operate on specified user's crontab
-i Prompt before removing crontab
FILE Install crontab from file

Cron Syntax

# Format: minute hour day month weekday command # Fields: 0-59 0-23 1-31 1-12 0-7 command # Examples: 0 2 * * * /path/to/script.sh # Daily at 2:00 AM 30 14 * * 1 /path/to/weekly.sh # Mondays at 2:30 PM 0 */6 * * * /path/to/every6h.sh # Every 6 hours */15 * * * * /path/to/every15m.sh # Every 15 minutes
Field Range Special Values
Minute 0-59 * (every minute)
Hour 0-23 * (every hour)
Day 1-31 * (every day)
Month 1-12 * (every month)
Weekday 0-7 (0,7=Sunday) * (every day)

Basic Usage

Managing crontab

# Edit your crontab crontab -e # List current crontab crontab -l # Remove all cron jobs crontab -r # Remove with confirmation crontab -i -r # Install crontab from file crontab mycron.txt # Backup current crontab crontab -l > crontab_backup.txt

Basic crontab management operations

Simple scheduling examples

# Run every minute * * * * * echo "Hello World" >> /tmp/hello.log # Run every hour at minute 0 0 * * * * /home/user/hourly_task.sh # Run daily at 3:30 AM 30 3 * * * /home/user/daily_backup.sh # Run weekly on Sunday at midnight 0 0 * * 0 /home/user/weekly_cleanup.sh # Run monthly on the 1st at 2:00 AM 0 2 1 * * /home/user/monthly_report.sh

Common scheduling patterns

User-specific crontabs

# Edit another user's crontab (requires root) sudo crontab -u john -e # List another user's crontab sudo crontab -u alice -l # Remove another user's crontab sudo crontab -u bob -r # Install crontab for specific user sudo crontab -u charlie user_cron.txt

Manage crontabs for different users

Advanced Scheduling

Special time strings

# Special strings (not available on all systems) @reboot /home/user/startup.sh # Run at startup @yearly /home/user/yearly.sh # Run once a year (0 0 1 1 *) @annually /home/user/annual.sh # Same as @yearly @monthly /home/user/monthly.sh # Run once a month (0 0 1 * *) @weekly /home/user/weekly.sh # Run once a week (0 0 * * 0) @daily /home/user/daily.sh # Run once a day (0 0 * * *) @midnight /home/user/midnight.sh # Same as @daily @hourly /home/user/hourly.sh # Run once an hour (0 * * * *)

Special time strings for common intervals

Complex time patterns

# Every 15 minutes */15 * * * * /path/to/script.sh # Every 2 hours 0 */2 * * * /path/to/script.sh # Weekdays only (Monday to Friday) 0 9 * * 1-5 /path/to/weekday.sh # Specific days of the month 0 0 1,15 * * /path/to/bimonthly.sh # Multiple times per day 0 6,12,18 * * * /path/to/threetimes.sh # Business hours (9 AM to 5 PM, weekdays) 0 9-17 * * 1-5 /path/to/business.sh # Every 10 minutes during business hours */10 9-17 * * 1-5 /path/to/frequent.sh

Complex scheduling patterns

Environment and variables

# Set environment variables in crontab SHELL=/bin/bash PATH=/usr/local/bin:/usr/bin:/bin [email protected] HOME=/home/user # Use variables in commands 0 2 * * * $HOME/scripts/backup.sh # Set specific environment for a job 0 3 * * * cd /app && /usr/bin/python3 manage.py cleanup # Redirect output 0 4 * * * /path/to/script.sh > /var/log/cron.log 2>&1 # Suppress output 0 5 * * * /path/to/quiet.sh >/dev/null 2>&1

Environment configuration and output handling

Practical Examples

System maintenance tasks

# System backup every night at 2 AM 0 2 * * * /usr/local/bin/system_backup.sh # Clean temporary files daily at 3 AM 0 3 * * * find /tmp -type f -mtime +7 -delete # Update system packages weekly 0 4 * * 0 apt update && apt upgrade -y # Rotate logs weekly 0 5 * * 0 /usr/sbin/logrotate /etc/logrotate.conf # Check disk space every hour 0 * * * * df -h | mail -s "Disk Space Report" [email protected] # Restart service daily 0 6 * * * systemctl restart myservice

Common system maintenance cron jobs

Application tasks

# Database backup every 6 hours 0 */6 * * * mysqldump -u backup -p'password' mydb > /backup/db_$(date +\%Y\%m\%d_\%H\%M).sql # Send daily reports 0 8 * * * cd /app && python3 generate_report.py # Clean old files every week 0 1 * * 0 find /app/uploads -type f -mtime +30 -delete # Process queue every 5 minutes */5 * * * * cd /app && php artisan queue:work --stop-when-empty # Generate sitemap daily 0 2 * * * cd /var/www/html && php generate_sitemap.php # Send newsletter weekly 0 9 * * 1 cd /app && python3 send_newsletter.py

Application-specific cron jobs

Monitoring and alerts

# Check website availability every 5 minutes */5 * * * * curl -f http://example.com >/dev/null || echo "Website down" | mail -s "Alert" [email protected] # Monitor disk usage hourly 0 * * * * df -h | awk '$5 > 80 {print $0}' | mail -s "Disk Usage Alert" [email protected] # Check service status every 10 minutes */10 * * * * systemctl is-active --quiet myservice || systemctl restart myservice # Log system stats every 15 minutes */15 * * * * echo "$(date): $(uptime)" >> /var/log/system_stats.log # Check for failed login attempts daily 0 7 * * * grep "Failed password" /var/log/auth.log | tail -10 | mail -s "Failed Logins" [email protected] # Monitor memory usage */30 * * * * free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }' >> /var/log/memory.log

System monitoring and alerting

Development and deployment

# Pull latest code and deploy every hour 0 * * * * cd /app && git pull origin main && ./deploy.sh # Run tests daily 0 1 * * * cd /app && npm test > /var/log/test_results.log 2>&1 # Clear cache every 4 hours 0 */4 * * * cd /app && php artisan cache:clear # Backup database before deployment 55 23 * * * mysqldump myapp > /backup/pre_deploy_$(date +\%Y\%m\%d).sql # Generate documentation weekly 0 2 * * 0 cd /app && make docs # Clean build artifacts daily 0 3 * * * cd /app && make clean

Development and deployment automation

Troubleshooting

Common issues and solutions

# Check if cron daemon is running systemctl status cron systemctl status crond # On some systems # View cron logs tail -f /var/log/cron tail -f /var/log/syslog | grep cron journalctl -u cron -f # Test cron job manually # Run the exact command from crontab /path/to/script.sh # Check script permissions ls -la /path/to/script.sh chmod +x /path/to/script.sh # Verify PATH in cron environment * * * * * echo $PATH > /tmp/cron_path.txt # Test with full paths 0 * * * * /usr/bin/python3 /full/path/to/script.py

Troubleshoot common cron issues

Debugging cron jobs

# Add logging to cron jobs 0 2 * * * /path/to/script.sh >> /var/log/myscript.log 2>&1 # Create a test cron job * * * * * echo "Cron is working: $(date)" >> /tmp/cron_test.log # Check environment variables * * * * * env > /tmp/cron_env.txt # Verify user permissions * * * * * whoami > /tmp/cron_user.txt # Test script with cron environment #!/bin/bash # Add to script for debugging echo "Script started at $(date)" >> /var/log/debug.log echo "Current directory: $(pwd)" >> /var/log/debug.log echo "PATH: $PATH" >> /var/log/debug.log echo "USER: $USER" >> /var/log/debug.log

Debug cron job execution

Best Practices

Crontab Best Practices
  • Use absolute paths for commands and scripts
  • Set appropriate environment variables (PATH, SHELL, etc.)
  • Redirect output to log files for debugging
  • Test scripts manually before adding to crontab
  • Use meaningful comments in crontab entries
  • Set MAILTO for error notifications
  • Backup crontab before making changes
  • Use locking mechanisms for long-running jobs
Common Pitfalls
  • Environment differences - Cron has minimal environment
  • Path issues - Commands may not be found without full paths
  • Permissions - Scripts must be executable
  • Output handling - Unhandled output can cause issues
  • Time zones - Cron uses system time zone
  • Overlapping jobs - Long-running jobs may overlap

See also