使用Windows任务栏运行Codeigniter控制器

jgzswidk  于 2023-11-14  发布在  Windows
关注(0)|答案(1)|浏览(119)

我想定期运行一个CodeIgniter控制器使用Windows任务调度器像一个cron作业。我已经运行了一个独立的PHP文件使用任务调度器与this方法,但未能实现这一对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()方法。

qgelzfjb

qgelzfjb1#

将write_file()设置为private或protected方法,以禁止浏览器使用它。在服务器上设置crontab(如果是Linux,或者如果是Windows服务器,则设置Time Schedule)。使用$path的完整路径(即$this->path = APPPATH . "cron_test" . DIRECTORY_SEPARATOR;)。使用双重检查来查看是否发出了请求。类似于:

<?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


(This一个人每天中午都会采取行动)。

相关问题