我們在寫程式的時候,可能都會遇到需要定時執行某個程式的需求,如果在 Linux 就會使用 CronJob 來幫我們排程定時執行,這邊來說一下怎麼透過 CronJob 來執行 CodeIgniter 的程式。
首先準備一個 Controller:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cron extends CI_Controller
{
/**
* This is default constructor of the class
*/
public function __construct()
{
parent::__construct();
$this->load->library('input');
}
public function autoRun()
{
// is_cli_request() is provided by default input library of codeigniter
if($this->input->is_cli_request())
{
//do something
}
else
{
echo "You dont have access";
}
}
}
注意上面那段 $this->input->is_cli_request() 就是用來判斷只有透過指令碼執行這段程式才能動,不能透過網頁來跑這段。
接著撰寫 CronJob :
0 0 0 0 0 php-cli /your_site_folder/index.php cron autoRun
注意前面的數字代表執行週期,會需要修改,而 your_site_folder 一樣要改成你的網站放的位置,這樣設定好就能夠排程執行了。