使用Windows任务计划程序运行Codeigniter控制器(Cron作业)

时间:2016-01-24 06:20:08

标签: php codeigniter cron taskscheduler

我想使用Windows任务计划程序(如cron作业)定期运行CodeIgniter控制器。我使用this方法使用任务调度程序运行独立的php文件,但未能在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()方法。

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分: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