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 :

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 :

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/ /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!