Cron jobs are automated tasks executed at specified intervals in Unix-like operating systems. These tasks can be scheduled to run by minute, hour, day of the month, month, day of the week, or any combination thereof. They’re invaluable for system maintenance and administration tasks such as database backups, security updates, disk space checks, and email notifications.
Among the most common cron schedules are those that run tasks every 5, 10, or 15 minutes. This guide will walk you through setting up these frequent cron jobs effectively.
Understanding Crontab Syntax
Crontab (cron table) is a configuration file that defines cron job schedules. You can manage these files using the crontab
command.
Each line in a user’s crontab file contains six fields:
* * * * * command(s)
│ │ │ │ │
│ │ │ │ └─── Day of week (0 - 7, where 0 and 7 are Sunday)
│ │ │ └────── Month (1 - 12)
│ │ └───────── Day of month (1 - 31)
│ └──────────── Hour (0 - 23)
└─────────────── Minute (0 - 59)
Crontab Operators
*
: Represents all allowed values-
: Specifies a range of values (e.g., 1-5),
: Defines a list of values (e.g., 1,3,5)/
: Sets step values (e.g., */5 for “every 5 units”)
To edit your crontab file, use the command crontab -e
.
Setting Up Frequent Cron Jobs
Running a Job Every 5 Minutes
There are two methods to achieve this:
- Using the comma operator:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * command
- Using the step operator (recommended):
*/5 * * * * command
Running a Job Every 10 Minutes
Use the following crontab entry:
*/10 * * * * command
Running a Job Every 15 Minutes
Add this line to your crontab:
*/15 * * * * command
Best Practices and Tips
- Test your commands: Before adding a command to crontab, ensure it works correctly when run manually.
- Use absolute paths: Cron jobs run with a limited environment, so use full paths to commands and files.
- Redirect output: To capture errors or results, redirect output to a log file:
*/5 * * * * command > /path/to/logfile.log 2>&1
- Set a proper MAILTO: If you want to receive job outputs via email, set the MAILTO variable in your crontab:
MAILTO=[email protected]
*/5 * * * * command
- Use comments: Add comments to your crontab entries for better maintainability:
# Backup database every 15 minutes
*/15 * * * * /path/to/backup_script.sh
Conclusion
Mastering frequent cron jobs can significantly enhance your system’s efficiency and automation capabilities. By understanding the crontab syntax and utilizing the step operator, you can easily set up tasks to run at 5, 10, or 15-minute intervals. Remember to regularly review and optimize your cron jobs to ensure they continue to meet your system’s needs.
Feel free to leave a comment if you have any questions about setting up or managing these frequent cron jobs!