Introduction to Cronjobs in Codeigniter

Codeigniter runs based on the front controller pattern where all the requests are routed using the index.php file. So if we want to execute any code on codeigniter application, we have to go through this routing procedure. Consider a situation where we want to use a cronjob to execute some code on the application. Normally we create the code files and put it on a server location and call the files directly in the cron job using the path to files(Ex: /var/www/html/ExampleApp/cron.php ). In codeigniter applications its difficult to call this scripts and use codeigniter models inside this scripts. You will have to load all the required models and files manually. Also codeigniter libraries cannot be called in the default way.Considering above points its better to write the code for the cronjob normally inside codeigniter controllers and call it remotely using the crontab. We cannot achieve this using normal php script calling procedure.

Using Curl in Executing Cronjob

Introduction to Curl

PHP Curl extension is used to transfer data from server to another server using various methods. In this example we need to execute a remote url using normal http method in curl.

Installing Curl

Installing method of curl various according to the operating system. I’ll show you how to install curl in some of the popular operating systems.

You have to allow the curl extension by removing ‘;’ in the php.ini file and restart apache server.

Type the following command in the terminal using the super user.

yum install php-curl

Type the following command in the terminal using the super user.

apt-get install php-curl

Setting the Cronjob using Curl

You can set up the cronjob to call the codeigniter url using the following line of code.
*/5 * * * * /usr/bin/curl
  • Open the crontab using the terminal and enter the above line of code and restart the cron.
  • Use the path to the curl file according to your installed location.
  • Call the cron function of your site remotely using http.

Related Posts