2014-02-26 94 views
-2

我想從cron作業運行此腳本。在CakePHP中添加Cron作業

我有網址爲這次行動www.abc.com/leads/generatedai​​lyreport

我要天天跑這個URL被打,使我PROGRAME運行。請幫忙。

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 = '[email protected]'; 
      $this->Email->from ='[email protected]'; 
      $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 = '[email protected]'; 
     $this->Email->from ='[email protected]'; 
     $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; 

} 
+0

你可能想要使用類似curl來每天獲取頁面。你可能會更好地問某個地方,如[服務器故障](http://serverfault.com/);這與編程無關。 –

回答

1

這不是一個cakePHP工作。您可以使用您的cpanelhosting。在做你cpanel找到crond jobsscheduled tasks ..從那裏你必須把你的期望file path並適當timingscronjob .. ,如果你的軟管提供商犯規提供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。他們會引導你進一步...

+0

沒有來自cron jon,我們無法找到任何網頁對於此URL www.abc.com/leads/generatedai​​lyreport 我想要這個URL,讓我知道有什麼方法每天自動點擊這個URL – user3251674

+0

@ user3251674對不起。 。我沒有得到你... –

+0

當我點擊一個URL「www.mywebsite.com/leads/generatedai​​lyreport」 這將發送所有每日報告到不同的不同的電子郵件地址,現在我想運行這個腳本使用cron作業,由於CAKE PHP我不能設置成這個URL的cron,因爲cron需要至少一個帶擴展名.php的文件,現在讓我知道什麼是方法,以便我可以將這個URL設置爲cron。 – user3251674

4

使用Shell腳本。 您不希望機器人或其他人直接在URL中訪問您的cron。

App/Console/Command中創建殼。

如果你有ssh訪問,使用crontab,你需要添加類似:

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

More info here

+0

請讓我知道銷售腳本,我使用的是CAKE PHP 2.3.0 – user3251674

+1

你能查看這個頁面http://book.cakephp.org/2.0/en/console-and-shells.html並設置腳本作爲cron?然後嘗試將其添加到crontab?我不能給出一個更清晰的例子,除了正式文件 – cornelb

+0

我已經看過他們的文件,但可以寫劇本。 – user3251674

0

HELLO FRND您可以輕鬆地在蛋糕PHP創建的cron喬恩

 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 /選擇/ LAMPP/htdocs中/ JobFinder /應用/比進入

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