I want to run a CodeIgniter controller periodically using Windows Task Scheduler like a cron job. I have run stand alone php file using task scheduler with this method but failed to implement this on a CodeIgniter controller.
Here is my controller:
<?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");
}
}
I want to run index()
method periodically.
Any help will be highly appreciated.
Make your write_file() as private or protected method to disallow use of it from browsers. Set crontab on your server (if Linux, or Time Schedule if Windows server). Use full path of $path
(ie $this->path = APPPATH . "cron_test" . DIRECTORY_SEPARATOR;
). Use double check to see if cli request is made. Something like:
<?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");
}
}
Than, on your server set crontab. That could looks something like:
* 12 * * * /var/www/html/index.php cli/Cron_test
(This one would make action every day at noon). Cron reference on Ubuntu .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.