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
*/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.