Creating CRON jobs in Kohana 3.x is a piece of cake

Do you need to run some batch processes periodically via CRON? Kohana makes that a piece of cake. You can run any controller/method from the command line and it will act as if you had visited that page with a browser. You do that with a command similar to this:

php index.php --uri=cron/testjob

In the example, cron is name of the controller and testjob is name of the method that you want to run. Since cron jobs are generally not meant to be accessible from the web, we need to add a little something in to the constructor of the cron controller. Check the example controller below.

<?php defined('SYSPATH') or die('No direct script access.');
 
class Controller_Cron extends Controller {
 
        public function __construct()
        {
                if(!Kohana::$is_cli)
                {
                        // This works in Kohana 3.1+
                        // It throws up a 404 page if someone is trying to request this
                        // controller from web. We only allow it to be executed from command line
                        throw new HTTP_Exception_404('The requested page does not exist!');
 
                        // In Kohana versions previous to 3.1, you can use the following code to achieve the same effect:
 
                        /*
                        $this->request->status = 404;
                        $this->request->send_headers();
                        exit;
                        */
 
                        // The main idea here is to kill the script if someone is trying to
                        // access it from the web.
                }
        }
 
        public function action_testjob()
        {
                // Maybe do some database updates here
                echo "nUpdating database...";
 
                // Send some files to a remote FTP
                echo "nSending files to FTP...";
 
                // Do some wrap up stuff...
                echo "nWrapping up job...";
 
                echo "nJob Finished!nn";
        }
 
} // End Cron Controller
 
?>

It is as simple as that. Note that the above controller is just a sample. You can name your “cron controller” what ever you like. The point here is that you can run any controller/method easily from the command line and add things to your crontab.

The output of the example above would be the following.

user@UBUNTU:~/kohana-3.2$ php index.php --uri=cron/testjob
 
Updating database...
Sending files to FTP...
Wrapping up job...
Job Finished!
 
user@UBUNTU:~/kohana-3.2$

  1. Dave says:

    Simple but informative post. Thanks a lot!

  1. There are no trackbacks for this post yet.