Here is how I run cron scripts in the CI environment, it ended up being very easy:
cron scripts are generally going to be doing maintenance things such as database updates, cache file management, sending emails, etc. Things with generated output like emails I want to come from view files. The db updates will use existing data models. cache file cleaning will use custom CI libraries. Therefore, it is important to me to have the CI environment available to my cron script.
What is not necessary is an HTTP connection. Why involve the web server? All you are doing is adding an unnecessary TCP stack setup and teardown, creating unwanted access_log entries, not to mention more security checks and timeout issues.
The slight problem is that CI expects an HTTP connection environment to make everything work happy. But actually, all CI really needs for a cron script is the PATH_INFO. That is how CI knows what controller/method to use, etc. So, we can emulate this.
First, make a directory for your cron scripts. I just used scripts and put it in the same directory that my CI system folder is in. Then, copy the index.php file from your DOCUMENT_ROOT (the script that normally initiates a connection to CI from a web browser) to the scripts directory, and rename it to something meaningful, such as clean_cache.php.
Now, we edit this file and make some slight adjustments. First, we don’t want the script to timeout during execution, so somewhere toward the top we add:
set_time_limit(0);
Next, we need to set the path to the system folder, if it isn’t correct:
$system_folder = "../system";
Next, we need to let CI know what controller/method we want to access, and any other URI variables we need. Normally this happens in the URL, so we emulate it by setting PATH_INFO manually:
$_SERVER['PATH_INFO'] = '/cron/cleancache';
Next, you create a cron.php controller (in the system/controllers dir) with a cleancache method, and make it do what it needs to do. load libraries/models/etc, execute them, then exit. What you don’t want to happen is output anything. Just make sure you don’t echo any content to stdout (echo, loading views, etc.) If you are sending emails, you would load a view file, but return the contents to a variable instead of displaying it (pass true as third param), then run through normal procedures for sending emails.
One thing to be aware of regarding security, you probably don’t want anyone accessing /cron/cleancache from a web browser, so in the cron.php controller constructor, you may want to do some kind of check to make sure we are coming from a cron script. Probably the easiest method would be to test the SCRIPT_FILENAME variable:
if($_SERVER['SCRIPT_FILENAME'] != 'clean_cache.php')
exit;
Once everything looks good, add your crontab entry to execute the script, and there you have it!