User:Pegeraki/HB Cron

From WolfTech
Jump to navigation Jump to search

WolfTech Webteam Handbook

Cron Jobs

Cron jobs are scripts that run automatically on a regular basis. This might be daily, weekly, or some other interval (they can run as often as every minute). This kind of script usually updates database information, does integrity checks, etc. In other words, if you find yourself running a script in the web browser quite often just to update system information, you probably want to change it run as a cron job instead. The scripts do not have to be written in a specific language, but we'll only talk about using PHP here.

To write your script so it can run as a cron job, you really only need to make one small change. At the top of the script, before any other PHP code or HTML, put the following line:

#!/afs/ -q

This ensures that the machine which runs the cron job runs it as a PHP script. Remember, no web browser is involved here, so this line makes sure the script is invoked correctly.

Other than that single line, your script does not really need anything else in terms of code. If it worked in a web browser, it should now work as a cron job as well. However, outputting information with echo statements is not really useful since ther is no easy way of viewing outputs. Therefore, it is a good idea to have the script send an email when it is done. The email could contain information on database rows inserted/updated/deleted and if any errors occurred or unexpected behavior. It could also contain the total execution time, which is especially useful if the script takes a while to run (i.e. more than just a few seconds). In other words, any information you think might be useful should go in the email. If the script runs more than once a day, it might be annoying to get an email every time. If this is the case, consider sending emails only when errors occur.

Only a person with special access to the cron server can actually schedule the cron job. Once your done with the script (make sure it runs in a browser, then add the above line), ask someone with access to schedule it for you (this will most likely be whoever gave you the task in the first place).