使用 Windows 任务计划程序运行 Codeigniter 控制器

问题描述 投票:0回答:1

我想使用 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()
方法。

php codeigniter windows-task-scheduler
1个回答
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

(这个每天中午都会行动)。 Ubuntu 上的 Cron 参考

© www.soinside.com 2019 - 2024. All rights reserved.