12 February, 2008

crontab tips on GoDaddy

This was nowhere in the GoDaddy documentation so, I though I would share a working solution.

The objective was to create a single php script which a set of scheduled crontab tasks could execute from my GoDaddy virtual dedicated server. I wanted something that ran hourly, daily, weekly and monthly.

The steps I used were:

1. Create your script in the normal way. The key element is the $_SERVER['argv']['1'] variable, which is passed from the crontab line. You could pass more than one. The second would be $_SERVER['argv']['2']. You might add this for a checksum to prevent the script running if the search engines find it. I then used the first variable in a switch group to establish the start and end date for a MySQL query that runs later. So:

switch ($_SERVER['argv']['1']) {

case "hourly": // RUNS AT *:00
$d2 = date("Y-m-d H",time()).":00:00";
$d1 = date("Y-m-d H",strtotime($d2) - 3600).":00:00";
$num = 1;
break;

case "daily": // RUNS AT 00:20
$d2 = date("Y-m-d",time() - 24 * 3600);
$d1 = date("Y-m-d",strtotime($d2) - 24 * 3600);
$num = 2;
break;

case "weekly": // RUNS AT 00:40
$d2 = date("Y-m-d",time() - 24 * 3600);
$d1 = date("Y-m-d",strtotime($d2) - 7 * 24 * 3600);
$num = 3;
break;

case "monthly": // RUNS AT 01:00
$d2 = date("Y-m-d",time() - 24 * 3600);
$d1 = date("Y-m-d",strtotime($d2) - 24 * 3600 * 365.25 / 12);
$num = 4;
break;

}

$query2 = "SELECT *
FROM `".$type[$j]."`
WHERE DATE(`".$col[$j]."`) > '".$d1."'
AND DATE(`".$col[$j]."`) <= '".$d2."'";

2. Chmod this file to 'rwx r-x r-x' to allow it to be executed by the server.

3. Add a scheduled task like this:

10 0 * * * /usr/bin/php /var/www/vhosts/yourdomain/httpdocs/cron/alerts.php hourly
20 0 * * * /usr/bin/php /var/www/vhosts/yourdomain/httpdocs/cron/alerts.php daily
30 0 * * 1 /usr/bin/php /var/www/vhosts/yourdomain/httpdocs/cron/alerts.php weekly
40 1 1 * * /usr/bin/php /var/www/vhosts/yourdomain/httpdocs/cron/alerts.php monthly

I have the file in a directory called cron, but you can put it where you like.

Any HTML output your script creates will then be sent to the email address set in the preferences tab where you set up scheduled tasks. This is for error reporting so make your script produce no HTML if it is working fine.