While working on a personal project, I discovered I could use a cron_dispatcher. The only problem is I was not certain that the 1.1 version of the cron_dispatcher would work in CakePHP 1.2, so I tried it. The results were frightening… at first. I set everything up and ran the cron from the command line and … Segmentation Fault! EEEK! So I started digging. I soon found there were some simple tweaks to apply to get the 1.1 cron_dispatcher to work.
First, copy and paste the webroot/index.php to your app directory and rename to cron_dispatcher.php.
Edit the bottom of the cron_dispatcher.php. You will replace:
if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {
return;
} else {
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch($url);
}
if (Configure::read() > 0) {
echo "<!-- " . round(getMicrotime() - $TIME_START, 4) . "s -->";
}
with
define(CRON_DISPATCHER,true);</code>
<code>if($argc == 2) {
$Dispatcher= new Dispatcher();
$Dispatcher->dispatch($argv[1]);
}
Next, add your cron function to the controller you will be using for the cron. You must add a few security lines to the function call within the controller. This will prevent someone from calling your cron from a URL. It will also prevent the view from being called when the cron is running, since the view is not needed.
function cron_function(){</code>
<code>// Check the action is being invoked by the cron dispatcher (security)
if (!defined('CRON_DISPATCHER')) { $this->redirect('/'); exit(); }
$this->layout = null; // turn off the layout</code>
<code>// do something (place your cron action here)</code>
<code>exit;</code>
<code>}
Now the final and most critical part. You must make sure debug, in app/core/config.php is set to 0. If not, you will get the segfault.
A note About Auth
In my application, I am using the Auth component. This is a great way to provide security to your application. It just so happens that I have Auth turned on globally for my app. This means that you can’t even view the home page without logging in. So I have app/app_controller.php set up with var $components = array('Auth'); to accomplish this. So when I try to run my cron from the command line, it denies access to the cron_function and reroutes me to the login.
To get around auth, simply add the beforeFilter to the controller the cron function is called from.
function beforeFilter(){
// turn off auth for cron jobs
$this->Auth->allow('cron_function');
}
This is a much more effective solution than using wget for multiple reasons. Two of the biggest being 1) if you are using security, you can override it internally without the risk. 2) With wget you run into issues if the cron you are running takes awhile to process as it could cause a timeout.
There you have it. A working cron_dispatcher for CakePHP 1.2.
Follow Me (digitally you stalker)