Cron Jobs
Cron jobs are the Linux/UNIX world’s scheduler. Many people, myself included, have a hard time understanding crons. After all, setting one up is very simple, if you know what you are doing.
The Crontab
“crontab” is the utility you use to setup a cron job. Type “crontab -e” from the command prompt to edit your list of crons. It’s just a textfile with a special format. Each non-blank line is a cron job. The format of each line is 6 space separated fields. Here is what each field defines:
- Minute
- Hour (Military Time)
- Day of the Month
- Month
- Day of the Week (0 is Sunday, 1 is Monday, etc.)
- Program to run w/any arguments (may include spaces)
The Date/Time fields may be a specific number, a “*” meaning anything, a “*/x” meaning every x hours/minutes/etc., or a comma separated list of any or all of the above.
So, if you wanted a certain program to run every 30 minutes, you could say it any of these ways:
*/30 * * * * /path/to/program arg1 arg2 0,30 * * * * /path/to/program arg1 arg2 12,42 * * * * /path/to/program arg1 arg2
Use Absolute Paths
If you are writing a script to run as a cron, you must make sure your script uses full paths or it will throw an error. Yes, the script will execute without error when run from the command line, but the cron will crap out.
Examples
0 2 1 * * /home/apache/rotate-logs.sh
Runs the rotate-logs.sh script the first of every month at 2AM.
0 17 * * * /home/oddjob/send-margarita-time-email.sh
Runs the send-margarita-time-email.sh script at 5PM every day.
0 17 * * 1,2,3,4,5 /home/oddjob/send-margarita-time-email.sh
Runs the send-margarita-time-email.sh script at 5PM Monday – Friday.
0 4 * * 1 /usr/sbin/mysql_dump > /backup/mysql/backup-`date "+%Y-%m-%d"`
Performs a weekly backup of the mysql database Mondays at 4AM.
0 0 1,15 * * /home/accounting/payroll.pl
Runs payroll.pl on the first and fifteenth of every month at 12 midnight.
Points to remember
- Use full paths in scripts
- The crontab is only for the current user
Related posts:
- PVR Cron For about a year now, I’ve been playing around with...
- PVR Update In anticipation of TV shows coming back on, I’ve been...
- Blocked Port 25 Workaround Recently, I switched to AT&T DSL. I’m quite happy with...
- Using Subversion for Server Backups Last month, I lost the template for Barry Bakes. I...
Related posts brought to you by Yet Another Related Posts Plugin.