I hate scheduling cron tasks. It seems like a hidden beast. Its doing things while you sleep, while you eat, and even when you’re working. It’s like multitasking in another dimension!
Well I’ve noticed in my deploy process I sometimes forget about new cron tasks that have been in my dev branch for a while. Wouldn’t it be easier to have those scheduled as part of your CakePHP app? So with this SchedulerShell.php I can simply schedule one task for SchedulerShell.php, and add my schedule in bootstrap.php. So now when I create new tasks, and a month later when I deploy that task is sheduled within the project. I don’t have to update crontab every time.
It really is that easy, here are the steps to set it up.
First grab the SchedulerShell.php and drop it in your App/Console/Command directory.
Schedule this new SchedulerShell as a cron. You will want to schedule it to run as frequently as your most frequent task. For instance if you have tasks you want to run every 5 minutes, daily, and monthly, set your crontab to run at least every 5 minutes. The CakePHP book as some help on cronjobs.
We’re almost there, here comes the easy and fun part! In your bootstrap.php we are going to add entries for each task we want to run.
Configure::write('SchedulerShell.jobs', array( 'CleanUp' => array('interval'=>'next day 5:00','task'=>'CleanUp'),// tomorrow at 5am 'Newsletters' => array('interval'=>'PT15M','task'=>'Newsletter') //every 15 minutes ));
First I want to note that the key to each entry can be anything as long as it is unique.
Task is just that, the name of the task. You can run the same task at different intervals if you wish, just be sure to give that job a unique name as mentioned above. There are also two other optional arguments: “action” which defaults to “execute” and “pass” which defaults to “array()”.
I’ve been using this successfully for months on CarBounce.com with great success. See the readme file on Github for any up to date information on outstanding issues. Enjoy!