How to Run Cron Jobs in CodeIgniter
Posted on January 4, 2012 by Steve
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.
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”
(apache user 혹은 nginx user와 크론잡 유저가 다를 경우)
또한 Oracle DB를 사용 할 경우 Oracle Path, 시스템 환경 변수등이 크론잡 유저에 설정되어 있는지 확인해야 겠지요?
다 귀찮다면.. 문서에 있듯이 wget으로 돌려도 무방.. 단, REMOTE_ADDR등으로 접근을 막아주는 건 기본..