Cakephp 2.x Running Shell as Cron Job on shared hosting

I was working on a project using cakephp (Version 2.5.2) and I need to run shell as cron jobs on my shared hosting server. I faced some issues executing the shell from the cpanel, so I thought about writing this quick tutorial to help other who are struggling with running cron jobs on shared hosting.

Writing the Shell

  • I created new shell called Mycron and saved it to app/Console/Command/MycronShell.php
  • In my shell I needed to use User model and Email components, so I added the imports. My Shell looks like this:
<?php 
App::uses('CakeEmail', 'Network/Email');

class MycronShell extends AppShell {
	
	public $uses = array('User','Message');	
}
  • I wanted to send a reminder email to use to activate his/her account. so I added the following remind_user function
public function remind_user(){
   $conditions = array('conditions'=>array('User.active'=>false));
   $inactive_users = $this->User->find('all',$conditions);
   foreach($inactive_users as $inactive){
      $this->sendRemiderEmail($inactive);
   }

}

  • Now my shell is ready. I needed to add the cronjob in my cpanel. The recommend way to run a shell as cron job from the documentation of cakephp is
cd /full/path/to/app && Console/cake myshell myparam
  • I have modified the permission of app/Console/cake to 754
  • In my cpanel I registered the cron using the following command
/home/user/public_html/app/Console/cake -app /home/user/public_html/app mycron remind_user > /home/user/public_html/logfile.txt 2>&1

 

  • mycron is the name of the shell i created (MycronShell) and the first parameter (remind_user) is the function name.
  • The last part /home/user/public_html/logfile.txt 2>&1 I used it to log the execution status, if you dont want to log it then you can use /dev/null 2>&1 instead

That is it, I hope this helps