I didn’t like managing all of my website’s CRON jobs via CPanel because I couldn’t easily see what my jobs were and when they will run next. So I decided to manage the CRON in my applications database and with a simple PHP script. You will need to only create 1 CRON job in Cpanel and this will subsequently run all the other jobs you define! Here are a couple easy steps on how to do it with Codeigniter 3.0.
Manage CRON Jobs with PHP/MySQL and Codeigniter 3.0
- Create the following MySQL Database:
CREATE TABLE `cron` ( `id` int(5) NOT NULL, `name` varchar(100) DEFAULT NULL, `command` varchar(255) NOT NULL, `interval_sec` int(10) NOT NULL, `last_run_at` datetime DEFAULT NULL, `next_run_at` datetime DEFAULT NULL, `is_active` tinyint(1) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- Create the file application/libraries/CronRunner.php with the following contents:
<?php defined('BASEPATH') or exit('No direct script access allowed'); class CronRunner { private $CI; public function __construct() { $this->CI =& get_instance(); } private function calculateNextRun($obj) { return (time() + $obj->interval_sec); } public function run() { $query = $this->CI->db->where('is_active', 1)->where('now() >= next_run_at OR next_run_at IS NULL', '', false)->from('cron')->get(); if ($query->num_rows() > 0) { $env = getenv('CI_ENV'); foreach ($query->result() as $row) { $cmd = "export CI_ENV={$env} && {$row->command}"; $this->CI->db->set('next_run_at', 'FROM_UNIXTIME('.$this->calculateNextRun($row).')', false)->where('id', $row->id)->update('cron'); $output = shell_exec($cmd); $this->CI->db->set('last_run_at', 'now()', false)->where('id', $row->id)->update('cron'); } } } }
- Create application/controllers/Cron.php with the following contents:
<?php if (! defined('BASEPATH')) { exit('No direct script access allowed'); } class Cron extends MY_Controller { public function __construct() { parent::__construct(); if (!$this->input->is_cli_request()) { show_error('Direct access is not allowed'); } } public function run() { $this->load->library('core/CronRunner'); $cron = new CronRunner(); $cron->run(); } }
- Log into Cpanel and create a Cron job that runs every 1 minute that calls the above Cron->run() method
- Insert the jobs you want to run and the interval in the database table that we defined above!