Scheduling tasks with Crontab
Crontab allows tasks to be scheduled to run regularly at a set interval, or at a repeating set time. This is very useful for running daily or weekly reports, updating the ports and source monthly, or for checking that a process is running and starting it if it is not.
Setting the editor for Crontab
Crontab uses the default editor specified by your shell. Normally this defaults to vi. If you are running tcsh and wish to change it edit your .cshrc and to set the default editor to ee, pico, or an editor of your choice
setenv EDITOR ee
Editting Crontab
To get to your crontab type
crontab -e
This will take you to the crontab for the user you are currently logged in as. If you wish to specify a different user to run the command as you can place it in /etc/crontab file where the user can be specified. When you edit crontab it will be automatically saved and installed.
Crontab Syntax
rdate (/usr/ports/sysutils/rdate) can be used to get the correct time. If we were to schedule rdate to run on the 5th day of the week at 11:30pm
#minute hour mday month wday command # 30 23 * 5 * ~/sync.sh
Script sync.sh
#!/bin/sh /usr/local/sbin/rdate -s time.nist.gov >/dev/null 2>&1
Notice that this task ends with the output being sent to /dev/null. This removes any error messages or any output given by the task. Anything that is not sent to /dev/null or another place will be emailed to you.
Times in Crontab can also be represented as */3 to denote that it runs everytime that number is a multiple of 3. For example if we wanted run a task every 3 hours to check if a process was running it might look like this
#minute hour mday month wday command # 20,40 */3 * * * ~/joe/psybncchk
This will be ran at 3:20, 3:40, 6:20, 6:40 and so on around the clock.
Removing tasks from Crontab
Tasks can be removed from crontab by either deleting the line, or by simply putting a # in front of the line.