jump to navigation

Poor mans Cron Component March 27, 2006

Posted by rossoft in CakePHP.
trackback

You must hack it a bit, because I use some constants and ‘configuracion’ component for storing the interval dates.

Usage: in beforeFilter() of AppController:
$this->cron->add(‘/mycontroller/cleanup’);

<?php
/*
 * Cron component
 * Executes tasks after rendering the output to the user at
 * certains time intervals.
 *
 * @author      RosSoft
 * @version     0.1
 * @license        MIT
 *
 */

class CronComponent extends Object
{
    var $controller;
    var $tareas=array();
    var $components=array(‘configuracion’,’requestHandler’);
    function startup(&$controller)
    {
        $this->controller=$controller;                       
    }
   
    /**
     * Adds a task to the list
     * @param string $tarea CakeURL of the action (/controller/action)
     */   
    function add($accion)
    {       
        $this->tareas[]=$accion;
    }
   
    function __destruct()
    {
        if (CONFIG_CRON_INTERVAL) //if 0 then disabled
        {
            $lastrun=$this->configuracion->value(‘CONFIG_CRON_LASTRUN’);
           
            $nextrun = $lastrun + 60 * CONFIG_CRON_INTERVAL;
            if (time()>$nextrun)
            {
                flush();
                if (! isset($this->requestHandler)
                    || ! $this->requestHandler->isAjax())
                {
                    $this->_execute_tasks();
                }
            }
        }
    }
   
   
    /**
     * Executed after flushed the page to the user, it the
     * call isn’t ajax.
     * It must call the programmed tasks if the timeout has
     * expired.
     */
    function _execute_tasks()
    {
        //a near future date for auto error recovering
        $this->configuracion->update(‘CONFIG_CRON_LASTRUN’,time() – CONFIG_CRON_RETRY_INTERVAL);           
        foreach ($this->tareas as $t)
        {
            @$this->controller->requestAction($t);           
        }
        $this->configuracion->update(‘CONFIG_CRON_LASTRUN’,time()+CONFIG_CRON_INTERVAL);
    }
}     

Advertisements

Comments»

1. Ryan - July 27, 2006

I dont suppose you can give an example of what the configuation file looked like? thanks 🙂

2. Ryan - July 27, 2006

or maybe the whole configuration component 🙂 just after some ideas


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: