<?php
class QCore_Bl_JobScheduler
{
    var $timestarted;
    var $maxtimetorun;

    //--------------------------------------------------------------------------
    // virtual
    function getJobClass($rtype)
    {
    }

    //--------------------------------------------------------------------------
    // virtual
    function scheduleJobs()
    {
    }

    //--------------------------------------------------------------------------

    function processJobs()
    {
        $sql = 'select jobid, rtype from wd_g_jobs where rstatus in ('._q(JOB_RUNNING).', '._q(JOB_NEW).') '.
               'order by datecreated asc, rstatus desc, rtype asc';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$rs || $rs->EOF) {
            return true;
        }

        while (!$rs->EOF && !$this->interrupt()) {
            if (!($jobClass = $this->getJobClass($rs->fields['rtype'])))
                continue;

            $job = QUnit_Global::newObj($jobClass);
            if ($job->loadJob($rs->fields['jobid'], $this)) {
                $job->start();
                $job->process();
            }

            $rs->MoveNext();
        }
    }

    //--------------------------------------------------------------------------

    function process()
    {
        $this->timestarted = time();
        $max_execution_time = ini_get('max_execution_time');
        if ($max_execution_time > 0) {
            $this->maxtimetorun = ($max_execution_time == '') ? 20 : ini_get('max_execution_time')-10;
        } else {
            $this->maxtimetorun = 999999;
        }

        $this->scheduleJobs();
        $this->processJobs();
    }

    //--------------------------------------------------------------------------

    function interrupt()
    {
        if (time() - $this->timestarted > $this->maxtimetorun) {
            return true;
        }
        return false;
    }

    //--------------------------------------------------------------------------

    function existsJob($type, $date1, $date2) {
        $sql = 'select jobid from wd_g_jobs where rtype='._q($type).
               ' and datecreated >= '._q(date("Y-m-d H:i:s", $date1)).
               ' and datecreated <= '._q(date("Y-m-d H:i:s", $date2));

        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);

        if(!$rs || $rs->EOF) {
            return false;
        }

        return true;
    }
}
?>
