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.
Table of Contents
Manage CRON Jobs with PHP/MySQL and Codeigniter
Automating tasks in web applications can significantly enhance efficiency and reliability. In CodeIgniter 3.0, integrating cron jobs with MySQL allows developers to schedule tasks like database backups, email notifications, and data cleanups seamlessly.
- 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!
FAQs
How do I check if my cron job is running correctly?
You can check your cron job by logging the output of the command to a file. Modify your crontab entry to append output to a log file, like this: /usr/bin/php /path_to_your_project/index.php croncontroller your_scheduled_task >> /path_to_log/cron.log 2>&1
. Additionally, you can check your database for expected updates if your cron job interacts with MySQL.
How do I prevent unauthorized access to my cron job controller?
To secure your cron job controller, ensure that it can only be accessed via the command line. You can check if the script is running in CLI mode by using php_sapi_name()
. If it’s not running in CLI mode, exit the function to prevent web-based access.
How can I schedule a cron job to run at a specific time?
Cron jobs use a five-field format to define schedules. For example, 0 2 * * *
runs a script at 2 AM every day. You can customize this format based on your needs. Tools like crontab.guru help in generating the correct syntax.
What should I do if my cron job is not executing?
If your cron job is not working, check for permission issues, ensure the script has executable rights, and verify that the PHP binary path in the cron command is correct. You can also try running the command manually via SSH to debug any errors.
Can I run cron jobs on a shared hosting server with limited access?
Yes, but it depends on the hosting provider. Many shared hosting services offer a control panel (such as cPanel) with a built-in cron job manager. Instead of using the command line, you may need to set up the cron job using a URL-based approach, calling your script via a web request.