使用 Windows 任务计划程序(Cron 作业)运行代码点火器控制器


Run Codeigniter controller using Windows Task Scheduler (Cron job)

我想像cron作业一样使用Windows任务调度程序定期运行CodeIgniter控制器。我已经使用此方法使用任务计划程序运行了独立的 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()方法。

任何帮助将不胜感激。

将 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

(这个会在每天中午采取行动)。Ubuntu 上的 cron 引用。