PHP: running scheduled jobs (cron jobs)

That's what cronjobs are made for. man crontab assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.


I'm answering this now because no-one seems to have mentioned this exact solution.

On a site I'm currently working on, we've set up a cron job using cPanel, but instead of running the PHP Interpreter directly (because we're using CodeIgniter and our code is mapped to a controller function, this probably isn't a great idea) we're using wget.

wget -q -O cron_job.log http://somehost/controller/method

-q is so that wget won't generate any output (so you won't keep getting emails). -O cron_job.log will save the contents of whatever your controller generates to a log file (overwritten each time so it won't keep growing).

I've found this to be the easiest way of getting 'proper' cron working.


If you have a cPanel host, you can add cron jobs through the web interface.Go to Advanced -> Cron Jobs and use the non-advanced form to set up the cron frequency. You want a command like this:

/usr/bin/php /path/to/your/php/script.php

Have you ever looked ATrigger? The PHP library is also available to start creating scheduled tasks without any overhead.

Disclaimer: I'm among their team.


if you're wondering how to actually run your PHP script from cron, there are two options: Call the PHP interpreter directly (i.e., "php /foo/myscript.php"), or use lynx (lynx http://mywebsite.com/myscript.php). Which one you choose depends mostly on how your script needs its environment configured - the paths and file access permissions will be different depending on whether you call it through the shell or the web browser. I'd recommend using lynx.

One side effect is that you get an e-mail every time it runs. To get around this, I make my cron PHP scripts output nothing (and it has to be nothing, not even whitespace) if they complete successfully, and an error message if they fail. I then call them using a small PHP script from cron. This way, I only get an e-mail if it fails. This is basically the same as the lynx method, except my shell script makes the HTTP request and not lynx.

Call this script "docron" or something (remember to chmod +x), and then use the command in your crontab: "docron http://mydomain.com/myscript.php". It e-mails you the output of the page as an HTML e-mail, if the page returns something.

#!/usr/bin/php
<?php

$h = @file_get_contents($_SERVER['argv'][1]);

if ($h === false)
{
        $h = "<b>Failed to open file</b>: " . $_SERVER['argv'][1];
}

if ($h != '')
{
        @mail("[email protected]", $_SERVER['argv']['1'], $h, "From: [email protected]\nMIME-Version: 1.0\nContent-type: text/html; charset=iso-8859-1");
}

?>