Practical Cron Job Examples
Let’s explore some real-world cron job examples that system administrators use daily. These practical applications demonstrate how cron can transform tedious manual tasks into automated processes that run reliably in the background.
Backup Automation with Cron
Creating regular backups is essential for data protection. With cron, you can schedule automatic backups without manual intervention.
# Daily backup at 2:00 AM
0 2 * * * tar -czf /backup/home-$(date +\%Y\%m\%d).tar.gz /home/
This command creates a compressed archive of the /home
directory every day at 2 AM. The filename includes the current date for easy identification.
For more sophisticated backups, you can create a backup script:
# Weekly full backup on Sundays at 3:00 AM
0 3 * * 0 /usr/local/bin/backup-script.sh
Many administrators implement a rotation system for backups that keeps daily backups for a week, weekly backups for a month, and monthly backups for a year. This approach balances storage space with recovery options.
Database Maintenance Tasks
Database servers require regular maintenance to perform optimally. Cron jobs can handle these repetitive tasks automatically.
For MySQL or MariaDB databases, you can schedule regular backups:
# Database backup every 6 hours
0 */6 * * * mysqldump -u username -p'password' database > /backup/db-$(date +\%Y\%m\%d-\%H).sql
Database optimization is another critical task that benefits from automation:
# Optimize tables weekly
0 4 * * 0 mysqlcheck -o -u username -p'password' --all-databases
Log rotation prevents database logs from consuming too much disk space:
# Rotate and compress logs monthly
0 0 1 * * gzip /var/log/mysql/mysql-slow.log && mv /var/log/mysql/mysql-slow.log.gz /var/log/mysql/mysql-slow-$(date +\%Y\%m).log.gz && touch /var/log/mysql/mysql-slow.log
Web Server and Site Management
Web servers and sites require ongoing maintenance to ensure optimal performance and visibility.
For Apache servers, you can schedule regular log rotation:
# Rotate Apache logs weekly
0 0 * * 0 /usr/local/bin/rotate-apache-logs.sh
Generating and updating sitemaps helps search engines index your website:
# Update sitemap.xml daily at midnight
0 0 * * * /usr/bin/php /var/www/html/generate-sitemap.php > /var/www/html/sitemap.xml
Monitoring server health can alert you to potential issues:
# Check website availability every 30 minutes
*/30 * * * * curl -s https://yourwebsite.com > /dev/null || mail -s "Website Down Alert" [email protected]
You can also automate content updates like refreshing the robots.txt file or clearing cached content to improve site performance.
Cron Job Monitoring and Maintenance
Keeping track of your cron jobs ensures they run properly and maintain system health. Effective monitoring helps identify issues quickly while maintenance practices prevent problems before they occur.
Logging and Notifying Job Outcomes
Cron jobs run silently in the background, making logging essential for tracking their execution. By default, cron sends output to the user’s email, but you can redirect it to specific log files:
0 2 * * * /backup/script.sh >> /var/log/backup.log 2>&1
This command captures both standard output and errors in one file.
For more advanced notification options, you can configure email notifications at the end of your scripts:
0 3 * * * /path/to/script.sh && echo "Backup complete" | mail -s "Backup Status" [email protected]
Many admins use specialized tools to monitor cron execution. These tools watch for successful completions and alert when jobs fail or take too long.
Consider using a dedicated cron monitoring service for critical tasks that handles notifications automatically.
Handling Failed Jobs
When cron jobs fail, quick detection and recovery are crucial. Implement error checking in your scripts using exit codes:
if ! /usr/bin/important_task; then
echo "Task failed" | mail -s "Error Alert" [email protected]
/usr/bin/recovery_script
fi
Create retry mechanisms for intermittent failures:
- Progressive delays – Wait longer between each retry attempt
- Maximum retry limits – Prevent infinite retry loops
- Failure logging – Record each failure with timestamps
For database-related tasks, implement transactions that roll back on failure to prevent data corruption.
Set up a centralized log collection system to gather all cron job outputs for easier troubleshooting when problems occur.
Assuring Cron Security Practices
Securing cron jobs is vital since they often run with elevated privileges. Always follow the principle of least privilege by running jobs with the minimum required permissions.
Avoid using the root crontab when possible:
# Instead of adding to root's crontab
# Create a dedicated user with limited permissions
sudo useradd -r cronjob_user
sudo crontab -u cronjob_user -e
Regularly audit your crontabs to remove unnecessary or outdated jobs. Use the crontab -l
command to list all jobs for a user.
Protect script files used by cron with proper permissions:
chmod 700 /path/to/script.sh
chown authorized_user:authorized_group /path/to/script.sh
Be cautious with tasks that involve sensitive information like database credentials. Store passwords in protected files instead of including them directly in cron commands.