2016-01-24 45 views
1

我想要像使用cron作業一樣定期使用Windows任務計劃程序來運行CodeIgniter控制器。我用this方法使用任務調度程序運行獨立的php文件,但未能在CodeIgniter控制器上執行此操作。使用Windows任務計劃程序(Cron作業)運行Codeigniter控制器

這裏是我的控制器:

<?php 
defined("BASEPATH") OR exit("No direct script access allowed"); 

class Cron_test extends CI_Controller { 

    public $file; 
    public $path; 

    public function __construct() 
    { 
     parent::__construct(); 
     $this->load->helper("file"); 
     $this->load->helper("directory"); 

     $this->path = "application" . DIRECTORY_SEPARATOR . "cron_test" . DIRECTORY_SEPARATOR; 
     $this->file = $this->path . "cron.txt"; 
    } 

    public function index() 
    { 
     $date = date("Y:m:d h:i:s"); 
     $data = $date . " --- Cron test from CI"; 

     $this->write_file($data); 
    } 

    public function write_file($data) 
    { 
     write_file($this->file, $data . "\n", "a"); 
    } 
} 

我要定期運行index()方法。

任何幫助將不勝感激。

回答

0

將您的write_file()設置爲私有或受保護的方法,禁止在瀏覽器中使用它。在您的服務器上設置crontab(如果是Linux,或者時間表是Windows服務器)。使用完整路徑$path(即$this->path = APPPATH . "cron_test" . DIRECTORY_SEPARATOR;)。使用雙重檢查來查看是否有cli請求。 類似於:

<?php 
defined("BASEPATH") OR exit("No direct script access allowed"); 

class Cron_test extends CI_Controller 
{ 

    public $file; 
    public $path; 

    public function __construct() 
    { 
     parent::__construct(); 
     $this->load->helper("file"); 
     $this->load->helper("directory"); 

     $this->path = APPPATH . "cron_test" . DIRECTORY_SEPARATOR; 
     $this->file = $this->path . "cron.txt"; 
    } 

    public function index() 
    { 
     if ($this->is_cli_request()) 
     { 
      $date = date("Y:m:d h:i:s"); 
      $data = $date . " --- Cron test from CI"; 

      $this->write_file($data); 
     } 
     else 
     { 
      exit; 
     } 
    } 

    private function write_file($data) 
    { 
     write_file($this->file, $data . "\n", "a"); 
    } 
} 

比,在你的服務器上設置crontab。這可能看起來像這樣:

* 12 * * * /var/www/html/index.php cli/Cron_test 

(這一個會在中午每天做出行動)。 Cron reference on Ubuntu

+0

感謝您的幫助,但如果有一種方法可以通過這個'在Windows任務調度index'功能?.... 這裏我已經爲一個單一的PHP文件做.. 在**新建任務>動作>新的**選項卡我已經在'program/script'字段中傳遞了php.exe的路徑,在'add arguments'字段中傳遞了** -f C:\ wamp \ www \ cron.php **。這裏'cron.php'是我的文件,它週期性地運行.... 我該怎麼傳遞'add arguments'字段來爲控制器做這樣的事情,或者有另一種方法來做這樣的事情? –

+0

我對答案做了一些修改。現在試試。順便說一句。用評論中的代碼更新問題,使其更具可讀性。 – Tpojka

相關問題