How to Run Cron Jobs in CodeIgniter

After a fair bit of trawling Google, I got the impression that setting up a cron job in codeigniter was going to be a bit tricky.

The two potential solutions I discovered were:

  1. execute the “wget” command to replicate a normal browser request, which then exposes my cron functionality to the big wide world and creates some additional unnecessary overheads, or
  2. Create a bespoke front controller a bit like the existing index.php but specifically for cron jobs

Neither of these options sound particularly ideal to me, and thankfully, there is a better way (and it turned out to be a case of RTFM).

Firstly, just create a normal controller. I creatively called mine Cron.

class Cron extends CI_Controller {

    function __construct()
    {
        parent::__construct();

        // this controller can only be called from the command line
        if (!$this->input->is_cli_request()) show_error('Direct access is not allowed');
    }

    function foo($bar = 'bar')
    {
        echo "foo = $bar";
    }
}

Note the call to $this->input->is_cli_request() which ensures that this controller cannot be accessed directly from a url.

Next we setup our cron job as you would any other, except that you provide the path in a special format.

php /path/to/index.php controller_name method_name ["params"]

The first part is either the command “php” or your server path to php.

The second part is the absolute path to your CI front controller, eg. /path/to/index.php.

The third part is the controller name, followed by the method name, followed by optional parameters.

The CI manual gives the example:

php /path/to/index.php cron foo

If that doesn’t work you might need to specify your path to php. I set mine as follows:

/usr/local/bin/php -f /home/clinic/public_html/index.php cron foo

You can even pass parameters in quotes, which have the same effect as parameters in regular url requests!

/usr/local/bin/php -f /home/clinic/public_html/index.php cron foo “beer”

This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>