6 Steps to create cron jobs in cakephp

Step 1 – Creating your own shell file

Step 2 – Writing the functionality in that shell file

Step 3 – Creating a cakeshell file

Step 4 – Creating a component file(optional)

Step 5 – Run command line and test it

Step 6 – Set cron tab

STEP 1 – Creating your shell file:

Creat the Shell file

For cake version 1.3 >> Create a file named shellname.php

in the Project name/app/vendors/shells/

Example : app/vendors/shells/order.php

For  cake version 2.0 >> Create a file named shellnameShell.php

in the Project name/app/vendors/shells/

Example : app/Console/Command/orderShell.php

STEP 2 – Writing Functionality in that shell file:

<?php

class OrderShell extends Shell {

        function main() // main needs to define
        {
                App::import(‘Component’, ‘BusinessLogic’);
                $this->BusinessLogic = &new BusinessLogic();

                $option = !empty($this->args[0]) ? $this->args[0] : ”;
                echo ‘Cron started without any issue.’;

                switch ($option)
                {
                        case ‘first’:
                        $result= $this->BusinessLogic->first_method();
                        break;
                        case ‘second’:
                        $result= $this->BusinessLogic->deleteauto();
                        break;
                        default:
                        echo ‘No Parameters passed .’;
                }
        }
}

STEP 3 – Create a cakeshell file:

For cake version 1.3: create another file named cakeshell with out any extenstion in the same folder app/vendors/shells/

Refer Link: http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/The-CakePHP-Console.html#running-shells-as-cronjobs

For cake version 2.0: create another file named cakeshell with out any extenstion in the same folder app/Console/
Refer Link: http://book.cakephp.org/2.0/en/console-and-shells/cron-jobs.html#running-shells-as-cronjobs/

STEP 4 – Creating Components:

create a component file inside app/controllers/components/

example: business.php

<?php
class BusinessComponent extends Object
{
function first_method()
{
echo “First Method called at” .date(‘M d, Y h:i:s T’).” \n”;
}

function second_method()
{
echo “Second Method called at” .date(‘M d, Y h:i:s T’).” \n”;
}
}

?>

STEP 5 – Run Command Line:

For cake version 1.3 : Go to project_name/app/ folder
Run the following command and check that shell is working fine

Syntax: cake shellname optional parameters

Example: var/www/projectname/app/ cake order

For cake version 2.0: Go to project_name/app/ folder
Run the following command and check that shell is working fine

Syntax: cake shellname optional parameters

Example: var/www/projectname/app/Console/cake order

STEP 5 – Set Crontab:

Final step setting the timing of the cron
go to your command prompt and type crontab -

Syntax :

* * * * * /path of the shell folder(inside app folder)/cakeshell shellname parameter
-cli /usr/bin -console
/path of the console folder(outside app folder)/console -app /path of app folder/ >>
/home/annamalai/Desktop/file.log

Example cake 1.3:

*/2 * * * * /var/www/v3.0/php/app/vendors/shells/cakeshell order first -cli /usr/bin -console
/var/www/v3.0/php/cake/console -app /var/www/v3.0/php/app >> /home/annamalai/Desktop/file.log

Example cake 2.0:

 * * * * * /var/www/apps/app/Console/cakeshell my first -cli /usr/bin -console

/var/www/apps/Cake/Console/ -app /var/www/apps/app >> /home/annamalai/Desktop/file.log

PHP Quiz

1.What is the content of $c after the following code has executed?
$a = 2;
$b = 3;
$c = ($a++ * ++$b);

2. What is the Output of the following code or how many times it will execute?

function counter($start, &$stop)
{
if ($stop > $start)
{
return;
}
counter($start–, ++$stop);
}
$start = 5;
$stop = 2;
counter($start, $stop);

3. what will be the output ?
$num = 10;
function multiply(){
$num = $num * 10;
}
multiply();
echo $num;

4. <? echo (2) . (3 * (print 3)); ?>

5.<?
$a = 0×01;
$b = 0×02;
echo $a === $b >> $a;
?>

6.<?
$a = 3;
print ‘$a’;
?>

7.Is it possible to use feof () with a file opened by  fsockopen ()?

8.<? echo false; ?>

9.echo ’1′.print(2) + 3;

10. <? print null == NULL; ?>

11.Which feature is not supported in php5?

12.Data Hiding:
Public: Any one can access it
Protected: only descendants can access it
Private: Only you can access it
Final: No one can redeclare it
Abstract: Some one else will implement this

13. PHP only supports ‘is a ‘and ‘has a’ relations

14.There are only two naming conventions for constructors depending on which version of PHP you are using.<br/>
<b>Before PHP5 and PHP5:</b>
The naming convention was that the constructor had to have the same name as the class.<br/>
<b>After PHP5:</b>
If you are running PHP5 or above, you can use the old style or you can use “__construct” as the name for the constructor.

15.In PHP 5, what is the difference between using self and $this?
Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

PHP tips that you need to know

  • PHP only supports ‘is a ‘and ‘has a’ relations
  • There are only two naming conventions for constructors depending on which version of PHP you are using.
    Before PHP5 and PHP5: The naming convention was that the constructor had to have the same name as the class.
    After PHP5:If you are running PHP5 or above, you can use the old style or you can use “__construct” as the name for the constructor.

Setting Cron job with cakephp 2.0 in Easy steps:

 
Setting Cron job with cakephp 2.0 in Easy steps: 
 
In some cases we need to do some process automatically every day /every hour / every week. For this 
we can use the Cron job. To see more about Cron Job Click here.
 
This example will shows that sending email to customers every 6 hours based on some  conditions:
 
My Project name is Sample and the Sample folder contains the following folders:
Sample
  — app
   — Controller etc
  —  lib
  — vendors
  — plugins
 
 
Step 1:  Go to the following folder
           Project folder/app/Console/Command/ 
 
Step 2: Create a file named MyShell.php  (You can create the file as per your own risk like SampleShell, CalShell etc)
 
Step 3: Paste the following code in that file. 
 
<?php 
   class MyShell extends Shell {
    function main()
    {
        App::import(‘Component’, ‘BusinessLogic’);
        $businessLogic = & new BusinessLogicComponent();
        $businessLogic->initialize();
        $settings = $businessLogic->senReminderEmail();
           // senReminderEmail Mail function is defined in my Controller/Components/BusinessLogicComponent.php File
    }
    function expireMail()
    {
 App::import(‘Component’, ‘BusinessLogic’);
        $businessLogic = & new BusinessLogicComponent();
        $businessLogic->initialize();
        $settings = $businessLogic->senExpireEmail();
     // senExpireEmail Mail function is defined in my Controller/Components/BusinessLogicComponent.php File
    }
}
?>
 
 
Step 4 : Go to the following folder:   Project folder/app/Vendor/Shell/
            Inside that create a file name called cron.sh and paste the following code.  Give 777 permission to this file.
 #!/bin/bash
# lock logic for semaphore – http://mywiki.wooledge.org/BashFAQ/045
lockdir=/tmp/cron_sh.lock
echo >&2 “$(date ‘+%Y-%m-%d %H:%M:%S’)
 
 #################################################”
if mkdir “$lockdir”
 then    # directory did not exist, but was created successfully
     echo >&2 “successfully acquired lock: $lockdir”
 
##########################################################################################################
 
# —————————————————————–
# Project name —>
# =========
 
 
# Project folder/lib/Cake/Console/cake – app  Project folder/app cron
/var/www/Sample/lib/Cake/Console/cake – app /var/www/Sample/app cron
##########################################################################################################
rmdir “$lockdir”
 else
     echo >&2 “cannot acquire lock, giving up on $lockdir”
     exit 0
 fi 
 
Step 5: To check that the cron functions are working or not, Go to the following folder in terminal
 Project folder/app/  #example  /var/www/Sample/app
and run the following Command :
 /var/www/Sample/app$  Console/cake myshell
The above line will execute the main function that we written in the MyShell.php file
To call other function just Console/cake my function_name
example: Console/cake my expireMail
Check the above functions are executing without any errors. If it executes with out any error then go for next step
Step 6: Now we are going to set the crontab. Just go to the Project folder through terminal and type crontab -e
It will open the editor in that paste the following code:
#The below line will execute the function every 6 hours
# *  */6   *    *   * /var/www/Sample/app/Console/cakeshell  my -cli /usr/bin -console /var/www/Sample/lib/Cake/Console -app /var/www/Sample/app
 
#The below line will execute the function named “expireMail” from myshell.php every 6 hours and it will log the execution in to the Home/error_file.log file
# *  */6   *   *   * /var/www/Sample/app/Console/cakeshell  my -cli /usr/bin -console /var/www/Sample/lib/Cake/Console -app /var/www/Sample/app >> ~/error_file.log