Wednesday 16 May 2012

Creating Cron-Jobs in CodeIgniter (CI) using CLI - CodeIgniter on the Command Line

To make a Cron Job work in CodeIgniter, you basically need to follow three steps;
  • Create a Model class
  • Create a Cron_Jobs Class
  • Set the Cron-Jobs command in the webserver.
Please, use the below example for the reference.
Step - 1: Create a Model Class.
class Warning_model extends CI_Model {
class Warning_model extends CI_Model {
	public function __construct()
	{
		parent::__construct();
	}
	
	public function addReferenceVATRecord()
	{
		//print_r($_SERVER);die;
		$data = array(	'valid_from' => date('Y-m-d H:i:s'),
						'type_id' => '1',
						'vat_rate' => '22.5',		
						'vat_calc' => '0.27',
						'updated' => date('Y-m-d H:i:s'),
						'updated_by' => '1'
					);
					
		$this->db->insert('reference_vat', $data);
		
		return $this->db->insert_id();
	}
}
/* End of file warning_model.php. */
/* Location: ./application/model/warning_model.php. */
Step - 2: Create a Cron_Jobs Controller Class.
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cron_Jobs extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('Warning_model', 'm_warning');

		// Call the cron job in below format: 
		// # /usr/local/bin/php /home/admin/admincentre.trunk.rc/index.php cron_jobs cron_add_vat_record 
	}

	public function cron_update_taxes($action='Cron Jobs')
	{
		echo "Hello {$action}".PHP_EOL;
	}
	
	public function cron_add_vat_record()
	{
		if ( $this->input->is_cli_request() )
		{
			// echo 'Request From CLI';
			$id = $this->m_warning->addReferenceVATRecord();
			echo $id.' '.PHP_EOL; die;
		}
		else { 
			echo 'Sorry Guys, we are bit smart this time.'; die;
		}
		
		//echo $id.' '.PHP_EOL; die;
	}
}
/* End of file cron_jobs.php. */
/* Location: ./application/controller/cron_jobs.php. */
Step - 3: Set the Cron-Jobs command in the webserver.
// Use the Croj Job command in below format: 
# /usr/local/bin/php /home/admin/admincentre.trunk.rc/index.php cron_jobs cron_add_vat_record 

No comments:

Post a Comment

Please post any queries and comments here.