在CakePHP中添加Cron Job

时间:2014-02-26 08:31:00

标签: php cakephp cron

我想从一个cron作业运行这个脚本。

我有这个动作的网址www.abc.com/leads/generatedai​​lyreport

我想每天都要运行这个URL,以便我的程序可以运行。请帮忙。

 public function generatedailyreport() {

     $this->Lead->unbindModel(array('belongsTo' => array('Country','State','City','Course')), true);
     $currentDate=date('Y-m-d 00:00:00');
     $previousDate=date('Y-m-d 00:00:00',strtotime('-1 day'));

    // find Each Unniverty
    // Find all the university
    Controller::loadModel('University');
    $University = new University();
    $UniversityArray=$University->find('all',array(
         'conditions'=>array('University.status'=>1),
         'recursive'=>-1));

    //First Row of the xls file
    $listDetails[]=array('Name','Email Address','Contact Number','Query Text','University Name','Source','Created Date');
    $i=1;
    foreach($UniversityArray as $value)
    {

         $UniversityId=$value['University']['id'];
         $university_name=$value['University']['university_code'];
         $universityName=$value['University']['university_name'];
         $leadsDetails=array();
         $leadsDetails=$this->Lead->find('all',array(
             'conditions'=>array(
                                 'Lead.created BETWEEN DATE_SUB(CURDATE(), INTERVAL '.DAY_INTERVAL.' DAY)  AND CURDATE() ',
                                 //'Lead.created BETWEEN "'.$currentDate.'" AND "'.$previousDate.'"',
                                 'Lead.master_lead_type_id'=>0,
                                 'Lead.university_id'=>$UniversityId,
                     ),
             'fields' => array('COUNT(*) as TotalLeads','University.university_name','Lead.created'),
             'group' => array('Lead.university_id'), 
             'recursive'=>1
             ));

        //pr($leadsDetails);

        if(!empty($leadsDetails)){
            $totalLeads=$leadsDetails[0][0]['TotalLeads'];
            $AssignedUniversityName=$leadsDetails[0]['University']['university_name'];
            $QueryDate=date('d M, Y',strtotime($leadsDetails[0]['Lead']['created']));

            //Total Report Array
            $reportTotalArray[]=array(
                'University_Name'=>$AssignedUniversityName,
                'Total Lead'=>$totalLeads,
                'Date'=>$QueryDate,
                );
        }else{
            $totalLeads='';
            $AssignedUniversityName='';
            $QueryDate='';

        }

        if($totalLeads >0 ){
        $leadsFullDetails=array();
        $leadsFullDetails=$this->Lead->find('all',array(
             'conditions'=>array(
                                 'Lead.created BETWEEN DATE_SUB(CURDATE(), INTERVAL 10 DAY)  AND CURDATE() ',
                                 //'Lead.created BETWEEN "'.$currentDate.'" AND "'.$previousDate.'"',
                                 'Lead.master_lead_type_id'=>0,
                                 'Lead.university_id'=>$UniversityId,
                     ),
             'fields' => array( 'Lead.first_name',
                                'Lead.email_address',
                                'Lead.contact_number',
                                'Lead.query_text',
                                'Lead.registered_from_source',
                                'University.university_name',
                                'Lead.created'),
             'recursive'=>1
             ));

        // Creating XLS File and send it to Email
        // Find all the leads from respective university
        //pr($leadsFullDetails);
        if(!empty($leadsFullDetails))
        {
            foreach($leadsFullDetails as $data)
            {
                $listDetails[]=array(
                            $data['Lead']['first_name'],
                            $data['Lead']['email_address'],
                            $data['Lead']['contact_number'],
                            $data['Lead']['query_text'],
                            $data['University']['university_name'],
                            $data['Lead']['registered_from_source'],
                            $data['Lead']['created'],
                            );
            }
            //Make an array of all Leads
            $allLeadsArray[$universityName]=$listDetails;

            $filename='Lead_query_'.$university_name.'_'.time().'-'.date('y-m-d',strtotime($data['Lead']['created'])).'.xls';   
            $fp = fopen('../webroot/files/'.$filename, 'w');
            $fileNamexls='../webroot/files/'.$filename;
            foreach ($listDetails as $fields) 
            {
                fputcsv($fp, $fields, "\t", '"');
            }
            $listDetails[]=array('Name','Email Address','Contact Number','Query Text','University Name','Source','Created Date');
            fclose($fp);

            // Sending Emails with attachement
            $message="Total Lead Query: ".$totalLeads."\n\r";
            $message_2 ="Assigned University Name: ".$AssignedUniversityName;
            $message_3 ="Query Date: ".$QueryDate;
            $this->set('message',$message);
            $this->set('message_2',$message_2);
            $this->set('message_3',$message_3);

            if($UniversityId==1){
                $toEmail=UOL_EIILM_EMAIL;
                $bccEmailArray=BCC_EMAIL;
                global $ccArrayEIILM;
                $ccArray=$ccArrayEIILM;

            }else if($UniversityId==2){
                $toEmail=UOL_JRU_EMAIL;
                $bccEmailArray=BCC_EMAIL;
                global $ccArrayJRU;
                $ccArray=$ccArrayJRU;

            }else if($UniversityId==3){
                $toEmail=UOL_RAITECH_EMAIL;
                $bccEmailArray=BCC_EMAIL;
                global $ccArrayRAITECH;
                $ccArray=$ccArrayRAITECH;

            }else if($UniversityId==4){
                $toEmail=UOL_NIILM_EMAIL;
                $bccEmailArray=BCC_EMAIL;
                global $ccArrayNIILM;
                $ccArray=$ccArrayNIILM;

            }else if($UniversityId==5){
                $toEmail=UOL_RAI_EMAIL;
                $bccEmailArray=BCC_EMAIL;
                global $ccArrayRAI;
                $ccArray=$ccArrayRAI;

            }else if($UniversityId==6){
                $toEmail=UOL_IUC_EMAIL;
                $bccEmailArray=BCC_EMAIL;
                global $ccArrayIUC;
                $ccArray=$ccArrayIUC;

            }

            $this->Email->to =$toEmail;
            $this->Email->cc = array($ccArray);
            $this->Email->bcc = array($bccEmailArray);
            $this->Email->subject = 'Daily Query Report';
            $this->Email->replyTo = 'no-reply@iuc.org.in';
            $this->Email->from ='Daily_Report@iuc.org.in';
            $this->Email->template = 'daily_report'; // note no '.ctp'
            $this->Email->attachments =array($fileNamexls);
            $this->Email->sendAs = 'html';
            $this->Email->send();   
            $message='';
            $totalLeads='';
            $AssignedUniversityName='';
            $QueryDate='';
            $fileNamexls='';
            $ccArray='';
            $toEmail='';
            $listDetails='';

        }
    }

    $i++;
    }
    pr($allLeadsArray);

    // Send Final Email to Mr, Rai
    //pr($reportTotalArray);

    $message='';
    if(!empty($reportTotalArray)){
    foreach($reportTotalArray as $reportData){
        $message.="Assigned University Name: ".$reportData['University_Name'];
        $message.="<br/>";
        $message.="Total Lead Query: ".$reportData['Total Lead'];
        $message.="<br/>";
        $message.="Query Date: ".$reportData['Date'];
        $message.="<br/>";
        $message.="<br/><br/><br/><br/>";
    }
    //echo $message;
    $this->set('totalReport',$message);


    $leadsTotalFullDetails=$this->Lead->find('all',array(
             'conditions'=>array(
                                 'Lead.created BETWEEN DATE_SUB(CURDATE(), INTERVAL 10 DAY)  AND CURDATE() ',
                                 //'Lead.created BETWEEN "'.$currentDate.'" AND "'.$previousDate.'"',
                                 'Lead.master_lead_type_id'=>0
                     ),
             'fields' => array( 'Lead.first_name',
                                'Lead.email_address',
                                'Lead.contact_number',
                                'Lead.query_text',
                                'Lead.registered_from_source',
                                'University.university_name',
                                'Lead.created'),
             'recursive'=>1
             ));


        // Creating XLS File and send it to Email
        // Find all the leads from respective university
        //pr($leadsFullDetails);
        if(!empty($leadsTotalFullDetails))
        {

            foreach($allLeadsArray as $key=>$dataAll){
                $listAllDetailss[]=array($key,'','Total Lead-',count($dataAll),'','','','');
                $listAllDetailss[]=array('Name','Email Address','Contact Number','Query Text','University Name','Source','Created Date');
                foreach($dataAll as $leadsData){
                    $listAllDetailss[]=$leadsData;
                }
                $listAllDetailss[]=array('','','','','','','');
                $listAllDetailss[]=array('','','','','','','');
                $listAllDetailss[]=array('','','','','','','');
            }

            //$listAllDetails[]=array('Name','Email Address','Contact Number','Query Text','University Name','Source','Created Date');
            /*  
            foreach($leadsTotalFullDetails as $datas)
            {

            $listAllDetails[]=array(
                            $datas['Lead']['first_name'],
                            $datas['Lead']['email_address'],
                            $datas['Lead']['contact_number'],
                            $datas['Lead']['query_text'],
                            $datas['University']['university_name'],
                            $datas['Lead']['registered_from_source'],
                            $datas['Lead']['created'],
                            );
            }
            */
            $allfilename='LeadAllReport_'.time().'-'.date('y-m-d',strtotime($data['Lead']['created'])).'.xls';  
            $fpp = fopen('../webroot/files/'.$allfilename, 'w');
            $fileNamexls='../webroot/files/'.$allfilename;
            foreach ($listAllDetailss as $fieldss) 
            {
                fputcsv($fpp, $fieldss, "\t", '"');
            }

            fclose($fpp);

        $this->Email->to =ALL_TO_EMAIL;
        $this->Email->cc = array(ALL_TO_CC);
        $this->Email->bcc = array(ALL_TO_BCC);
        $this->Email->subject = 'Daily Query Report';
        $this->Email->replyTo = 'no-reply@iuc.org.in';
        $this->Email->from ='Daily_Report@iuc.org.in';
        $this->Email->template = 'daily_report_total'; // note no '.ctp'
        $this->Email->attachments =array($fileNamexls);
        $this->Email->sendAs = 'html';
        $this->Email->send();   

        // Delete All files after sending on emails
        echo "$i Mail Sent.";
    }
}
    die;

}

3 个答案:

答案 0 :(得分:4)

使用Shell脚本。 您不希望机器人或其他人直接在网址中访问您的cron。

贝壳是在App/Console/Command

中创建的

如果您有ssh访问权限,请使用crontab,您需要在其中添加以下内容:

0 9 * * * /var/www/site.com/vendors/cakeshell myShell -app myApp

More info here

答案 1 :(得分:1)

这不是cakePHP工作..您可以使用cpanel中的hosting来实现..在cpanel查找crond jobsscheduled tasks ..从那里你必须为你的file path提供所需的timings以及cronjob .. 如果您的软管提供商不提供cron作业,您可以使用putty创建cronjobs ..

http://php-opensource-help.blogspot.in/2010/03/how-to-set-up-cron-job-file-using-putty.html

让我简要解释一下。

天气你的cron作业是用corephp或cakephp编写的。 cron作业是计划任务,它们会根据为特定cronjob设置的所需时间自动从服务器触发..

您需要向您的托管服务提供商询问您希望在服务器上setup a cron job。他们会引导你进一步...

答案 2 :(得分:0)

HELLO frnd你可以轻松地在蛋糕php中创建cron jon

        class HelloShell extends AppShell 
        {
        public $uses=array('Jobs','JobFeeds','JobMapping','User');

             public function main() 
             {
               $this->out('Hello world.');
             }

    }

这是我放入app / console / command / HelloShell.php

的文件

我在ubantu终端有命令。           $ cd / opt / lampp / htdocs / JobFinder / app / than enter

      /opt/lampp/htdocs/JobFinder/app$ crontab -e

这将打开这样的命令行

     */1  *   *    *   *  cd /opt/lampp/htdocs/JobFinder/app && Console/cake hello $

    # Edit this file to introduce tasks to be run by cron.
    #
    # Each task to run has to be defined through a single line
    # indicating with different fields when the task will be run
    # and what command to run for the task
    #
    # To define the time you can provide concrete values for
    # minute (m), hour (h), day of month (dom), month (mon),
    # and day of week (dow) or use '*' in these fields (for 'any').#
    # Notice that tasks will be started based on the cron's system
    # daemon's notion of time and timezones.
    #
    # Output of the crontab jobs (including errors) is sent through
    # email to the user the crontab file belongs to (unless redirected).
    #
    # For example, you can run a backup of all your user accounts
    # at 5 a.m every week with:
                                  [ Unknown Command ]
    ^G Get Help  ^O WriteOut  ^R Read File ^Y Prev Page ^K Cut Text  ^C Cur Pos
    ^X Exit      ^J Justify   ^W Where Is  ^V Next Page ^U UnCut Text^T To Spell

您已为要完成的任务设置了计时器

public function insert()
    {
        App::import('Utility', 'Xml');
      //    $this->loadModel('Jobs');
        $this->Jobs->deleteAll(array('1 = 1'));

        $AllUrls=$this->JobFeeds->find('all');
        if(is_array($AllUrls) && count($AllUrls)>0 )
        {
            foreach($AllUrls as $urls)
            {
                $xml = Xml::build($urls['JobFeeds']['url']);
                //echo "<pre>";print_r($xml);die;
                $cat_id=$urls['JobFeeds']['job_category_id'];
                $feed_id=$urls['JobFeeds']['id'];
                foreach($xml as $items)
                {
                    foreach($items->item as $job)
                    {

                        App::import('Model', 'JobMapping');
                        $this->JobMapping = new JobMapping();
                        $AllData=$this->JobMapping->find('all',array('conditions'=>array('JobMapping.job_feeds_id'=>$feed_id)));

                        App::import('Model', 'Jobs');
                        $this->Jobs = new Jobs();
                       foreach($AllData as $allData)
                        {
                            $data['title']      =$job->$allData['JobMapping']['title'];
                            $data['description']=$job->$allData['JobMapping']['description'];
                            $data['link']       =$job->$allData['JobMapping']['link'];
                            $data['guid']       =$job->$allData['JobMapping']['guid'];
                            $data['pubDate']    =$job->$allData['JobMapping']['pubDate'];
                            $data['Updated_date']= date("Y-m-d H:i:s");
                            $data['inserted_date']= date("Y-m-d H:i:s"); 
                            $data['cat_id']     =$cat_id;
                            //echo "<pre>";print_r($data);
                            $this->Jobs->save($data);
                        }
                    }
                } 
            }
        }


    }

在此代码中,我已在数据库中的1分钟内插入数据(将自动更新我的工作表enter code here

与shell有关的常见事情是让它作为cronjob运行,以便偶尔清理数据库或发送新闻稿。这对于设置来说是微不足道的,例如:

  */5  *    *    *    *  cd /full/path/to/app && Console/cake myshell myparam
# *    *    *    *    *  command to execute
# │    │    │    │    │
# │    │    │    │    │
# │    │    │    │    \───── day of week (0 - 6) (0 to 6 are Sunday to Saturday,
  |    |    |    |           or use names)
# │    │    │    \────────── month (1 - 12)
# │    │    \─────────────── day of month (1 - 31)
# │    \──────────────────── hour (0 - 23)
# \───────────────────────── min (0 - 59)