How to execute cron job in codeigniter using PHP

Contents

Introduction to Cron jobs 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 cron job 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 Cron Job

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.

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

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

yum install php-curl

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

apt-get install php-curl

Setting the Cron Job using Curl

You can set up the cron job to call the codeigniter url using the following line of code.
*/5 * * * * /usr/bin/curl http://www.example.com/controller/cron_function
  • 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.

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

Leave a Comment