CakePHP Crontab

Due to the way that CakePHP rewrites URL requests with its router, it might seem confusing to execute a Crontab to run a controller action. I will show you how to set up a cron dispatcher so that you can execute all your different controller action schedules on a single file and pass the controller and action as an argument to the file so that the dispatcher will know which action to fire.

First off, you’ll need to create a duplicate of your index.php file inside of /app/webroot/. Once you have duplicated the file, rename it to cron_dispatcher.php and open it up for editing. On line #77 of your cron_dispatcher.php file, you will see the following :

if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
 	trigger_error("Can't find CakePHP core.  Check the value of CAKE_CORE_INCLUDE_PATH in app/webroot/index.php.  It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
 }

The code shown above includes the CakePHP core bootstrap.php file and of course, if the include fails, it triggers an error. So we’ll add an ELSE statement to this code so that we can fire our dispatcher if in fact the boostrap was successfully included. After adding your ELSE statement and the appropriate code to initialize the dispatcher, your code from line #77 should now look like this :

if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
 	trigger_error("Can't find CakePHP core.  Check the value of CAKE_CORE_INCLUDE_PATH in app/webroot/index.php.  It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
 } else {
 	define('CRON_DISPATCHER', true);
 	if($argc == 2) {
 		$Dispatcher = new Dispatcher();
 		$Dispatcher -> dispatch($argv[1]);
 	}
 }

And that’s it. You are ready to start executing cron schedules on this cron_dispatcher.php file and pass your controller together with the action as an argument. Here is an example crontab command :

* * * * * php -q /var/www/vhosts/domain.com/httpdocs/app/webroot/cron_dispatcher.php /products/cron/

The command will execute the the cron_dispatcher.php file and pass the argument “/products/cron/” to it. The argument is equivalent to any controller and action in your CakePHP system. So it is /controller/action/

Good luck! I hope this helps!

Comments

  1. By Charlotte

  2. By TommyO

  3. By Mike

  4. By Mike

  5. By nasim

  6. By Ritesh

  7. By Jordan

  8. By deepak

  9. By mark

  10. By Vibha

  11. By Vibha

  12. By Vibha

  13. By Chris

Leave a Reply