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:
- 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
- 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| 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, it probably means you don’t have the package php5-cli installed. On debian / ubuntu you can install this package as follows:
sudo apt-get install php5-cli
If you are not able to install packages, you can 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”
No comments:
Post a Comment