Archive

For: ‘Linux

Cron jobs with crontab

Tuesday, December 2nd, 2008

The cron daemon is a long running process that executes commands at specific dates and times on your linux server. To schedule one-time only tasks with cron, use at or batch. For commands that need to be executed repeatedly (e.g. hourly, daily or weekly), use crontab.

An example of a cronjob I recently created was to update website directory information to the local database. This task would run every hour continuously.

 

To create a task cd into the root directory of the website execute:

 

crontab filename

 

This will create a file with the name specified.

 

crontab -e

 

Will open the file for editing.

 

Cron allows you to add an “mailto” reference to notify yourself of the failure of a task. As much as the file should have been tested prior to running with cron. It will give you the ability to see execution issues that you may not have picked up during local testing. See example below:

 

PHP Fatal error:  Call to undefined method
Project::set_name() in /home/warren/public_html/codebase.com/includes/Project.php on line 24

 

My example below includes the mailto reference. As stated below this is optional.

 

MAILTO=warren@codeevolutoin.co.uk
minute hour day month day command-line-to-execute

 

  • minute 0-59 – The exact minute that the command sequence executes.
  • hour 0-23 – The hour of the day that the command sequence executes.
  • day 1-31 – The day of the month that the command sequence executes.
  • month 1-12 – The month of the year that the command sequence executes.
  • weekday 0-6 – The day of the week that the command sequence executes.
  • Sunday=0, Monday = 1, Tuesday = 2 etc

 

The way to include speratic entries is to use a comma. Then seperate each time reference by a space. The below example will execute my task at 6am, 1pm and 8pm on Monday, Wednesday and Friday of every week

 

0 6,13,20 * 1,3,5 * /location_of_my_site/includes/execute.php

 

In the example above the use of a * will make the job occur every instance for that time period.

 

For my particular task (Updating a database with webserver directory data). I had to execute my task every hour on the hour. See below.

 

0 * * * * /location_of_my_site/includes/execute.php

 

This will execute the file every hour. For testing I set the task to run every 15 minutes. The exaple for this is below.

 

0,15,30,45 * * * * /location_of_my_site/includes/execute.php