CakePHP Shells, and Cron Jobs

As part of the same project that resulted in my last posting, I needed to write several processes that would be managed by cron. In the past, at the Yahoo contract, we had come up with a way to do this involving a customized version of the basic CakePHP index.php file. However, his required us to place the cron code on the main controllers, and extra protections to ensure that the code was inaccessible from the main web interface. I was never thrilled with the solution, but it was the best we had at the time.

So for this project, I looked into the concept of ‘Shells’, which are basically command-line interfaces to a CakePHP application. It quickly became obvious that this was the best way to go about handling the cron jobs for a CakePHP application. It allows you to place all your sensitive cron code completely out of reach of the web facing part of the application, increasing security and decreasing complexity. It’s really quite simple as well.

The process is basically outlined in this section of the CakePHP manual, and should be simple enough to follow. The end result is code like this:

class BillingShell extends Shell {
	var $uses = array('OrderLineItem', 'Division');
 
	function main() {
		echo "Please specify which billing task to run. Currently, the only choice is 'daily'.\n\n";
	}
 
	function daily() {
		date_default_timezone_set('America/Denver');
		App::Import('Component','Cbg');
		$this->Cbg = new CbgComponent();
 
		$this->create_invoices();
		$this->process_invoices();
	}
 
	// Other functions not shown
}

And you can run it as a cron like this:

# m h  dom mon dow   command
*/5 * * * * /full/path/to/cakeshell billing daily -app /full/path/to/app
%d bloggers like this: