HeatWare.net header image
HeatWare.net
TwitterRSSEmail
  • Home
  • Windows
    • Windows 8
    • Windows 7
    • Windows Vista
    • Windows XP
  • Linux/Unix
  • Mac
  • Mobile
    • Android
    • iOS
    • Phones (Help / Resources)
  • Software / Programming
    • Free Software
    • Programming – General
    • PHP
    • Ruby/Rails
    • Quality Assurance (QA)
    • Software – General
    • Software Help
    • Databases
  • Cool Websites
  • Other
    • Deals & Bargains
    • News
    • Video Games
    • Hardware
    • Electronics
  • About

4 comments / March 15, 2016 / sood / Programming – PHP

Manage Cron Jobs with Codeigniter 3.0 and MySQL

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

  1. 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;
  2. 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');
           }
        } 
      }
    }
  3. 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();
     }
    }
  4. Log into Cpanel and create a Cron job that runs every 1 minute that calls the above Cron->run() method
  5. Insert the jobs you want to run and the interval in the database table that we defined above!

Related Posts

  • How to call JavaScript function from PHP
  • Create a compressed MySQL database dump/backup (Linux)
  • Useful tips for PHP developers using MySQL

codeigniter Cron PHP

4 comments… add one
  1. Keith McLaughlin October 21, 2016, 6:27 am

    What do you write for the ‘command’ when storing it in the database?

    It is the path to the controller method?

  2. Stephen February 1, 2017, 6:23 am

    Just adding a couple of fixes here.

    $this->load->library(‘core/CronRunner’); should be $this->load->library(‘CronRunner’);

    In you cron add php /{fullpath}/index.php Cron run

    Line 26 of cronrunner.php with shell_exec. I have updated it to
    $output = shell_exec(“php /{fullpath}/index.php “$cmd);

    This will allow me to write cron jobs in CI and have this run them. The format is index.php Controller Function

  3. hezzels July 3, 2018, 4:02 am

    What do you fill for the first record in the table cron ?

  4. apps August 21, 2018, 2:42 am

    How we will get the first inventory? please reply soon

Cancel reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • Why You Should Consider Diving Apps
  • How to Buy a Smartphone that Fits Your Budget
  • How to Overcome Frustrating PDF Stress
  • Convert PDF to Word: Easy, Reliable and Quality Conversion
  • PDF to Excel App ­ – A New Way of Handling Tricky Documents

Recent Comments

  • Valarie Walter on Basic Troubleshooting Steps for your Cell Phone
  • John Mists on A Brief History of Android OS
  • syarif on PostgreSQL: How to reload config settings without restarting database
  • Raghu on How to SSH to a server using Ruby – Part I
  • francisco clemente on Basic Troubleshooting Steps for your Cell Phone

Tags

ACSLS Android Bargain Cell Phones Cool Software Cool Websites Databases Deals Ebooks Facebook Free Software G2x Galaxy S5 iOS iPhone Kindle LG Linux Linux/Unix Mac Mobile mysql Office OpenStack OS X PHP Postgres PostgreSQL ruby Samsung Galaxy S6 Shell Smartphones Sun T-Mobile Tips Tips & Tricks Ubuntu Unix Virtualization VMWare Windows Windows 7 Windows 8 Windows Vista Windows XP

Latest Tweet

Follow @HeatwaredotNet

SP
@HeatwaredotNet

  • Why You Should Consider Diving Apps https://t.co/Is41cdUv2I #diving-apps
    about 6 years ago

All Categories

Other Links

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Copyright © 2015 — HeatWare