public static function cron()
 {
     foreach (eqLogic::byType('virtual') as $eqLogic) {
         $autorefresh = $eqLogic->getConfiguration('autorefresh');
         if ($eqLogic->getIsEnable() == 1 && $autorefresh != '') {
             try {
                 $c = new Cron\CronExpression($autorefresh, new Cron\FieldFactory());
                 if ($c->isDue()) {
                     try {
                         foreach ($eqLogic->getCmd('info') as $cmd) {
                             $value = $cmd->execute();
                             if ($cmd->execCmd() != $cmd->formatValue($value)) {
                                 $cmd->setCollectDate('');
                                 $cmd->event($value);
                             }
                         }
                     } catch (Exception $exc) {
                         log::add('virtual', 'error', __('Erreur pour ', __FILE__) . $eqLogic->getHumanName() . ' : ' . $exc->getMessage());
                     }
                 }
             } catch (Exception $exc) {
                 log::add('virtual', 'error', __('Expression cron non valide pour ', __FILE__) . $eqLogic->getHumanName() . ' : ' . $autorefresh);
             }
         }
     }
 }
 public function runCliAction()
 {
     $log_file = tempnam(ROOTPATH . '/var/scheduler', 'orange-scheduler-output');
     $this->load->model(['scheduler_model', 'scheduler_output_model']);
     $entries = $this->scheduler_model->catalog();
     foreach ($entries as $idx => $job) {
         if ($job->is_enabled && $job->trigger_valid) {
             $time = trim($job->minute . ' ' . $job->hour . ' ' . $job->day_of_month . ' ' . $job->month . ' ' . $job->day_of_week);
             try {
                 $cron = Cron\CronExpression::factory($time);
                 if (!$cron->isDue()) {
                     $cli = 'cd "' . WWW . '/";php index.php ' . trim($job->url, '/');
                     if ($job->add_log) {
                         $cli .= ' > ' . $log_file . ' 2>&1';
                     }
                     exec($cli);
                     if ($job->add_log) {
                         $log_output = trim(file_get_contents($log_file));
                         $this->scheduler_output_model->insert(['scheduler_id' => $job->id, 'created_on' => date('Y-m-d H:i:s'), 'output' => $log_output]);
                     }
                     @unlink($log_file);
                 }
             } catch (Exception $e) {
             }
             /* dump old logs */
             $this->scheduler_output_model->keep($job->id, $job->keep);
         }
     }
 }
Exemple #3
0
function new_switch($args)
{
    $switch_name = $args['jobname'];
    $description = $args['jobdescription'];
    $server = $args['jobserver'];
    $interval = $args['jobinterval'];
    //$scale = $args['intervalScale'];
    //$intervalSeconds = ($interval * $scale);
    //parse cron string
    $cron = Cron\CronExpression::factory($interval);
    //echo $cron->isDue();
    $next = $cron->getNextRunDate()->format('U');
    $previous = $cron->getPreviousRunDate()->format('U');
    $diff = $next - $previous;
    //$intervalFromCron = "";
    $switch_id = generate_switchid($switch_name, date('U'));
    $dbclient = db_connect("hostname", "username", "password", "dms");
    $query = "INSERT INTO `switches` (`id`, `switch_name`, `description`, `server`, `interval`, `switch_id`) VALUES ('', '{$switch_name}', '{$description}', '{$server}', '{$diff}', '{$switch_id}')";
    $results = $dbclient->query($query);
    if ($results) {
        $response['switch_id'] = $switch_id;
        return $response;
    } else {
        return false;
    }
}
 /**
  * Tests CronTaskController::isTaskDue
  */
 public function testIsTaskDue()
 {
     $runner = CronTaskController::create();
     $task = new CronTaskTest_TestCron();
     $cron = Cron\CronExpression::factory($task->getSchedule());
     // Assuming first run, match the exact time (seconds are ignored)
     SS_Datetime::set_mock_now('2010-06-20 13:00:10');
     $this->assertTrue($runner->isTaskDue($task, $cron));
     // Assume first run, do not match time just before or just after schedule
     SS_Datetime::set_mock_now('2010-06-20 13:01:10');
     $this->assertFalse($runner->isTaskDue($task, $cron));
     SS_Datetime::set_mock_now('2010-06-20 12:59:50');
     $this->assertFalse($runner->isTaskDue($task, $cron));
     // Mock a run and test that subsequent runs are properly scheduled
     SS_Datetime::set_mock_now('2010-06-20 13:30:10');
     CronTaskStatus::update_status('CronTaskTest_TestCron', true);
     // Job prior to next hour mark should not run
     SS_Datetime::set_mock_now('2010-06-20 13:40:00');
     $this->assertFalse($runner->isTaskDue($task, $cron));
     // Jobs just after the next hour mark should run
     SS_Datetime::set_mock_now('2010-06-20 14:10:00');
     $this->assertTrue($runner->isTaskDue($task, $cron));
     // Jobs somehow delayed a whole day should be run
     SS_Datetime::set_mock_now('2010-06-21 13:40:00');
     $this->assertTrue($runner->isTaskDue($task, $cron));
 }
 protected function getCronExpression($line)
 {
     $cronLine = "";
     try {
         $cronLine = Cron\CronExpression::factory($this->getDateTime($line));
     } catch (Exception $e) {
     }
     return $cronLine;
 }
 public static function cron()
 {
     foreach (self::byType('networks') as $networks) {
         $autorefresh = $networks->getConfiguration('autorefresh');
         if ($networks->getIsEnable() == 1 && $autorefresh != '') {
             try {
                 $c = new Cron\CronExpression($autorefresh, new Cron\FieldFactory());
                 if ($c->isDue()) {
                     try {
                         $networks->ping();
                     } catch (Exception $exc) {
                         log::add('networks', 'error', __('Erreur pour ', __FILE__) . $networks->getHumanName() . ' : ' . $exc->getMessage());
                     }
                 }
             } catch (Exception $exc) {
                 log::add('networks', 'error', __('Expression cron non valide pour ', __FILE__) . $networks->getHumanName() . ' : ' . $autorefresh);
             }
         }
     }
 }
 public static function cronHourly()
 {
     foreach (self::byType('weather') as $weather) {
         if ($weather->getIsEnable() == 1) {
             $cron = cron::byClassAndFunction('weather', 'pull', array('weather_id' => intval($weather->getId())));
             if (!is_object($cron)) {
                 $weather->reschedule();
             } else {
                 try {
                     $c = new Cron\CronExpression($cron->getSchedule(), new Cron\FieldFactory());
                     if (!$c->isDue()) {
                         $c->getNextRunDate();
                     }
                 } catch (Exception $ex) {
                     if ($c->getPreviousRunDate()->getTimestamp() < strtotime('now') - 300) {
                         $weather->reschedule();
                     }
                 }
             }
         }
     }
 }
 /**
  * getParser.
  *
  * @param   string  $unix_mhdmd  Param
  *
  * @return	void
  */
 public static function getParser($unix_mhdmd = null)
 {
     JLoader::import('extly.helpers.cron_expression.FieldInterface');
     JLoader::import('extly.helpers.cron_expression.AbstractField');
     JLoader::import('extly.helpers.cron_expression.CronExpression');
     JLoader::import('extly.helpers.cron_expression.DayOfMonthField');
     JLoader::import('extly.helpers.cron_expression.DayOfWeekField');
     JLoader::import('extly.helpers.cron_expression.FieldFactory');
     JLoader::import('extly.helpers.cron_expression.HoursField');
     JLoader::import('extly.helpers.cron_expression.MinutesField');
     JLoader::import('extly.helpers.cron_expression.MonthField');
     JLoader::import('extly.helpers.cron_expression.YearField');
     return Cron\CronExpression::factory($unix_mhdmd);
 }
 public function newvalidatetimePostAction()
 {
     /* !todo get input and build trigger time */
     $time = trim($this->input->post('minute') . ' ' . $this->input->post('hour') . ' ' . $this->input->post('day_of_month') . ' ' . $this->input->post('month') . ' ' . $this->input->post('day_of_week'));
     $value = 0;
     $previous = '';
     $next = '';
     try {
         $cron = Cron\CronExpression::factory($time);
         $previous = $cron->getPreviousRunDate()->format("F j, Y, g:i a");
         $next = $cron->getNextRunDate()->format("F j, Y, g:i a");
         $value = 1;
     } catch (Exception $e) {
     }
     $this->output->json(['input' => $time, 'value' => $value, 'next' => $next, 'previous' => $previous]);
 }
 public function main()
 {
     App::import('Vendor', 'Cron/CronExpression');
     $this->out('Getting a list of all scheduled commands');
     $this->out("");
     $all_schedules = $this->Schedule->find('all');
     //go through each and determine if it should run or not
     foreach ($all_schedules as $schedule) {
         $cron_exp = Cron\CronExpression::factory($schedule['Schedule']['schedule']);
         if ($cron_exp->isDue()) {
             //run the command
             $this->out("Running " . $schedule['Command']['name']);
             //create the parameter array for this task
             eval("\$schedule_params = " . $schedule['Schedule']['parameters'] . ";");
             switch ($schedule['Schedule']['command_id']) {
                 case 1:
                     $this->RestrictedPrograms->execute($schedule_params);
                     break;
                 case 2:
                     $this->WakeComputer->execute($schedule_params);
                     break;
                 case 3:
                     $schedule_params['Restart'] = false;
                     $this->ShutdownComputer->execute($schedule_params);
                     break;
                 case 4:
                     $this->SendEmails->execute($schedule_params);
                     break;
                 case 5:
                     $this->DiskSpace->execute($schedule_params);
                     break;
                 case 6:
                     $schedule_params['Restart'] = true;
                     $this->ShutdownComputer->execute($schedule_params);
                     break;
             }
         } else {
             $this->out($schedule['Command']['name'] . " - Next Run: " . $cron_exp->getNextRunDate()->format('m-d-Y H:i:s'));
         }
     }
 }
Exemple #11
0
 /**
  * Checks e-mail and searches Actions that should be run
  *
  * @return array Array of Actions to execute
  * @throws ActionException
  */
 private function _checkEmail()
 {
     $sConfig = file_get_contents('EmailCheckingConfig.json');
     $aConfig = json_decode($sConfig, true);
     // Get accounts
     $aAccountsConfig = $aConfig['accounts'];
     // Get Actions
     $aActionsConfig = $aConfig['actions'];
     // Select Actions to run
     $aActionsToCheck = [];
     // Actions to run
     $aActionsToRun = [];
     foreach ($aActionsConfig as $aActionConfig) {
         // Check "check" parameter
         $oCron = Cron\CronExpression::factory($aActionConfig['check']);
         if ($oCron->isDue()) {
             $aActionsToCheck[] = $aActionConfig;
         }
     }
     // Check selected Actions for running letter
     foreach ($aActionsToCheck as $aActionConfig) {
         $aAccountConfig = $aAccountsConfig[$aActionConfig['account']];
         if ($oConnection = imap_open($aAccountConfig['server'], $aAccountConfig['user'], $aAccountConfig['password'])) {
             $oCheck = imap_check($oConnection);
             if ($oCheck->Nmsgs > 0) {
                 $aEmails = imap_search($oConnection, 'UNSEEN');
                 foreach ($aEmails as $iEmailNumber) {
                     $oOverview = imap_fetch_overview($oConnection, $iEmailNumber)[0];
                     // Match letter and Action run parameters
                     $bResult = preg_match('/' . $aActionConfig['email']['fromRegexp'] . '/i', $oOverview->from);
                     // Check subject patterns
                     $xCheckSubjectPatternsResult = $this->_checkSubjectPatterns($oOverview->subject, $aActionConfig['email']['subjectRegexp']);
                     $bResult = $bResult && $xCheckSubjectPatternsResult !== false;
                     if ($bResult) {
                         $aArguments = [$oOverview, imap_body($oConnection, $iEmailNumber), imap_fetchstructure($oConnection, $iEmailNumber)];
                         if (is_array($xCheckSubjectPatternsResult) && count($xCheckSubjectPatternsResult) > 0) {
                             $aArguments[] = $xCheckSubjectPatternsResult;
                         }
                         $aAction = ['name' => $aActionConfig['name'], 'args' => $aArguments];
                         if (isset($aActionConfig['registerPath'])) {
                             $aAction['registerPath'] = $aActionConfig['registerPath'];
                         }
                         $aActionsToRun[] = $aAction;
                         imap_delete($oConnection, $iEmailNumber);
                     }
                 }
             }
             imap_close($oConnection, CL_EXPUNGE);
         } else {
             throw new ActionException('Can\'t connect to mail server');
         }
     }
     return $aActionsToRun;
 }
 /**
  * Data provider for testBeforeSave
  * 
  * @return array
  */
 public function beforeSaveProvider()
 {
     return array(array(array('id' => 4, 'name' => 'Test4', 'active' => 1, 'cron' => '0 0 * * *', 'priority' => 1, 'last_check' => '0000-00-00 00:00:00'), array('id' => 4, 'name' => 'Test4', 'active' => 1, 'cron' => '0 0 * * *', 'priority' => 1, 'last_check' => '0000-00-00 00:00:00', 'next_check' => (new DateTime('tomorrow'))->format(Configure::read('Monitoring.dbDateFormat')))), array(array('id' => 4, 'name' => 'Test4', 'active' => 1, 'priority' => 1, 'last_check' => '0000-00-00 00:00:00'), array('id' => 4, 'name' => 'Test4', 'active' => 1, 'priority' => 1, 'last_check' => '0000-00-00 00:00:00', 'cron' => '0 15 * * *', 'next_check' => Cron\CronExpression::factory('0 15 * * *')->getNextRunDate('now')->format(Configure::read('Monitoring.dbDateFormat')))));
 }
 protected function _getNextRun($job)
 {
     $result = false;
     try {
         $cron = Cron\CronExpression::factory($job->frequency);
         $result = $cron->getNextRunDate(new DateTime('now', new DateTimeZone('UTC')));
     } catch (RuntimeException $e) {
         // never gonna run again :(
     }
     return $result;
 }
Exemple #14
0
 public static function cron()
 {
     //Rafraichissement des valeurs des modules
     foreach (eqLogic::byType('zwave') as $eqLogic) {
         $scheduler = $eqLogic->getConfiguration('refreshDelay', '');
         if ($scheduler != '') {
             try {
                 $c = new Cron\CronExpression($scheduler, new Cron\FieldFactory());
                 if ($c->isDue()) {
                     try {
                         foreach ($eqLogic->getCmd() as $cmd) {
                             $cmd->forceUpdate();
                         }
                     } catch (Exception $exc) {
                         log::add('zwave', 'error', 'Erreur pour ' . $eqLogic->getHumanName() . ' : ' . $exc->getMessage());
                     }
                 }
             } catch (Exception $exc) {
                 log::add('zwave', 'error', 'Expression cron non valide pour ' . $eqLogic->getHumanName() . ' : ' . $scheduler);
             }
         }
     }
     //Verification des piles une fois par jour
     if (date('H:i') == '00:00') {
         foreach (zwave::byType('zwave') as $eqLogic) {
             $http = new com_http(self::makeBaseUrl() . '/ZWaveAPI/Run/devices[' . $eqLogic->getLogicalId() . '].instances[0].commandClasses[0x80].Get()');
             try {
                 $http->exec();
             } catch (Exception $exc) {
             }
             $info = $eqLogic->getInfo();
             if (isset($info['state']) && $info['state'] == 'Réveillé') {
                 continue;
             }
             if (isset($info['battery']) && $info['battery'] !== '') {
                 $eqLogic->batteryStatus($info['battery']['value']);
             }
         }
     }
 }
Exemple #15
0
<?php

theme::header_start('Manage ' . $controller_titles, 'Manage all ' . $controller_titles . '. <span id="servertime"></span>');
Plugin_search_sort::field();
theme::header_button('new');
theme::header_end();
theme::table_start(['Enabled' => 'text-center', 'Description', 'When', 'URL', 'Keep' => 'text-center', 'Actions' => 'text-center'], [], $records);
foreach ($records as $record) {
    theme::table_start_tr('', 'text-center');
    theme::enum_icon($record->is_enabled);
    theme::table_row();
    theme::e($record->description);
    theme::table_row();
    $time = trim($record->minute . ' ' . $record->hour . ' ' . $record->day_of_month . ' ' . $record->month . ' ' . $record->day_of_week);
    try {
        $cron = Cron\CronExpression::factory($time);
        echo 'Previous: ' . $cron->getPreviousRunDate()->format("F j, Y, g:i a") . '<br>Next: ' . $cron->getNextRunDate()->format("F j, Y, g:i a");
    } catch (Exception $e) {
        echo '<span class="text-danger">Invalid trigger ' . $time . '</span>';
    }
    theme::table_row();
    theme::e($record->url);
    theme::table_row('text-center');
    theme::e($record->keep);
    theme::table_row('actions text-center');
    theme::table_action('edit', $this->controller_path . '/edit/' . $record->id);
    o_dialog::confirm_a_delete($this->controller_path . '/delete/' . $record->id);
    theme::table_action('eye', $this->controller_path . '/view/' . $record->id);
    theme::table_end_tr();
}
theme::table_end();
Exemple #16
0
<?php

$crons = cron::all();
foreach ($crons as $cron) {
    $c = new Cron\CronExpression($cron->getSchedule(), new Cron\FieldFactory());
    try {
        $c->getNextRunDate();
    } catch (Exception $ex) {
        $cron->remove();
    }
}
 /**
  * Checks and runs a single CronTask
  *
  * @param CronTask $task
  */
 public function runTask(CronTask $task)
 {
     $cron = Cron\CronExpression::factory($task->getSchedule());
     $isDue = $this->isTaskDue($task, $cron);
     // Update status of this task prior to execution in case of interruption
     CronTaskStatus::update_status(get_class($task), $isDue);
     if ($isDue) {
         $this->output(get_class($task) . ' will start now.');
         $task->process();
     } else {
         $this->output(get_class($task) . ' will run at ' . $cron->getNextRunDate()->format('Y-m-d H:i:s') . '.');
     }
 }
Exemple #18
0
 public static function cron()
 {
     if (!self::isStarted()) {
         config::save('enableScenario', 1);
         config::save('enableCron', 1);
         $cache = cache::byKey('jeedom::usbMapping');
         $cache->remove();
         foreach (cron::all() as $cron) {
             if ($cron->running() && $cron->getClass() != 'jeedom' && $cron->getFunction() != 'cron') {
                 try {
                     $cron->halt();
                 } catch (Exception $e) {
                 }
             }
         }
         try {
             jeedom::start();
         } catch (Exception $e) {
         }
         try {
             plugin::start();
         } catch (Exception $e) {
         }
         touch('/tmp/jeedom_start');
         self::event('start');
         log::add('core', 'info', 'Démarrage de Jeedom OK');
     }
     self::isDateOk();
     try {
         $c = new Cron\CronExpression(config::byKey('update::check'), new Cron\FieldFactory());
         if ($c->isDue()) {
             $lastCheck = strtotime(config::byKey('update::lastCheck'));
             if (strtotime('now') - $lastCheck > 3600) {
                 if (config::byKey('update::auto') == 1) {
                     update::checkAllUpdate();
                     jeedom::update('', 0);
                 } else {
                     config::save('update::check', rand(1, 59) . ' ' . rand(6, 7) . ' * * *');
                     update::checkAllUpdate();
                     $updates = update::byStatus('update');
                     if (count($updates) > 0) {
                         $toUpdate = '';
                         foreach ($updates as $update) {
                             $toUpdate .= $update->getLogicalId() . ',';
                         }
                         message::add('update', __('De nouvelles mises à jour sont disponibles : ', __FILE__) . trim($toUpdate, ','), '', 'newUpdate');
                     }
                 }
             }
         }
         $c = new Cron\CronExpression('35 00 * * 0', new Cron\FieldFactory());
         if ($c->isDue()) {
             cache::clean();
             DB::optimize();
         }
         $c = new Cron\CronExpression('02 02 * * *', new Cron\FieldFactory());
         if ($c->isDue()) {
             try {
                 log::chunk();
                 cron::clean();
             } catch (Exception $e) {
                 log::add('log', 'error', $e->getMessage());
             }
         }
         $c = new Cron\CronExpression('21 23 * * *', new Cron\FieldFactory());
         if ($c->isDue()) {
             try {
                 scenario::cleanTable();
                 user::cleanOutdatedUser();
                 scenario::consystencyCheck();
             } catch (Exception $e) {
                 log::add('scenario', 'error', $e->getMessage());
             }
         }
     } catch (Exception $e) {
     }
 }
Exemple #19
0
echo "[START CONSISTENCY]\n";
if (isset($argv)) {
    foreach ($argv as $arg) {
        $argList = explode('=', $arg);
        if (isset($argList[0]) && isset($argList[1])) {
            $_GET[$argList[0]] = $argList[1];
        }
    }
}
try {
    require_once dirname(__FILE__) . '/../core/php/core.inc.php';
    $crons = cron::all();
    if (is_array($crons)) {
        if (class_exists('Cron\\CronExpression')) {
            foreach ($crons as $cron) {
                $c = new Cron\CronExpression($cron->getSchedule(), new Cron\FieldFactory());
                try {
                    if (!$c->isDue()) {
                        $c->getNextRunDate();
                    }
                } catch (Exception $ex) {
                    echo "Suppression de  : " . $cron->getName() . ' car pas de lancement prévu';
                    $cron->remove();
                }
            }
        }
    }
    $cron = cron::byClassAndFunction('jeedom', 'persist');
    if (is_object($cron)) {
        $cron->remove();
    }
 function shouldRun(DateTime $date)
 {
     global $timedate;
     if (empty($date)) {
         $date = new DateTime();
     }
     $cron = Cron\CronExpression::factory($this->schedule);
     if (empty($this->last_run) && $cron->isDue($date)) {
         return true;
     }
     $lastRun = $timedate->fromDb($this->last_run);
     $next = $cron->getNextRunDate($lastRun);
     if ($next < $date) {
         return true;
     }
     return false;
 }
 /**
  * Checks and runs a single CronTask
  *
  * @param CronTask $task
  * @param boolean $forceRun
  */
 protected function runTask(CronTask $task, $forceRun = false)
 {
     $cron = Cron\CronExpression::factory($task->getSchedule());
     $isDue = $this->isTaskDue($task, $cron);
     $willRun = $isDue || $forceRun;
     // Update status of this task prior to execution in case of interruption
     CronTaskStatus::update_status(get_class($task), $willRun);
     if ($isDue || $forceRun) {
         $msg = ' will start now';
         if (!$isDue && $forceRun) {
             $msg .= " (forced run)";
         }
         $this->output(get_class($task) . $msg);
         // Handle exceptions for tasks
         $error = null;
         try {
             $result = $task->process();
             $this->output(CronTaskResult::PrettifyResult($result));
         } catch (Exception $ex) {
             $result = false;
             $error = $ex->getMessage();
             $this->output(CronTaskResult::PrettifyResult($result));
         }
         // Store result if we return something
         if (self::config()->store_results && $result !== null) {
             $cronResult = new CronTaskResult();
             if ($result === false) {
                 $cronResult->Failed = true;
                 $cronResult->Result = $error;
             } else {
                 if (is_object($result)) {
                     $result = print_r($result, true);
                 } else {
                     if (is_array($result)) {
                         $result = json_encode($result);
                     }
                 }
                 $cronResult->Result = $result;
             }
             $cronResult->TaskClass = get_class($task);
             $cronResult->ForcedRun = $forceRun;
             $cronResult->write();
         }
     } else {
         $this->output(get_class($task) . ' will run at ' . $cron->getNextRunDate()->format('Y-m-d H:i:s') . '.');
     }
 }
 /**
  * Returns the creation schedule as a CronExpression.
  * 
  * @see Cron\CronExpression::factory
  *
  * @return Cron\CronExpression The creation schedule
  */
 public function getCreationScheduleAsCronExpression()
 {
     ProjectConfiguration::registerCron();
     return Cron\CronExpression::factory(parent::getCreateNewEpisodesCronFormatted());
 }
 /**
  * Checks and runs a single CronTask
  *
  * @param CronTask $task
  */
 public function runTask(CronTask $task)
 {
     $canRunTask = true;
     $enforceSchedule = true;
     $isDue = true;
     if (method_exists($task, "canRunTask")) {
         $canRunTask = $task->canRunTask();
     }
     if (method_exists($task, "enforceSchedule")) {
         $enforceSchedule = $task->enforceSchedule();
     }
     if ($canRunTask) {
         if ($enforceSchedule) {
             $cron = Cron\CronExpression::factory($task->getSchedule());
             $isDue = $this->isTaskDue($task, $cron);
         }
         // Update status of this task prior to execution in case of interruption
         CronTaskStatus::update_status(get_class($task), $isDue);
         if ($isDue) {
             $this->output(get_class($task) . ' will start now.');
             $task->process();
         } else {
             $this->output(get_class($task) . ' will run at ' . $cron->getNextRunDate()->format('Y-m-d H:i:s') . '.');
         }
     } else {
         $this->output(get_class($task) . ' cannot run.');
     }
 }
 /**
  * {@inheritdoc}
  *
  * @param array $options
  * @return dool
  */
 public function beforeSave($options = array())
 {
     if (!empty($this->data[$this->alias]['cron'])) {
         $cron = $this->data[$this->alias]['cron'];
     } elseif (!empty($this->data[$this->alias]['id'])) {
         $cron = $this->field('cron', array('id' => $this->data[$this->alias]['id']));
     }
     if (!$cron) {
         $cron = Configure::read('Monitoring.defaults.cron');
     }
     $this->data[$this->alias]['cron'] = $cron;
     $this->data[$this->alias]['next_check'] = Cron\CronExpression::factory($cron)->getNextRunDate('now')->format(Configure::read('Monitoring.dbDateFormat'));
     return parent::beforeSave($options);
 }
 /**
  * get next date the cron needs to be run
  * @return date mysql format
  */
 public function get_next_date()
 {
     if ($this->loaded()) {
         //when is next? we used the started date as base
         require Kohana::find_file('vendor', 'autoload');
         //watch out for this in a futture may gave is troubles....
         $cron = Cron\CronExpression::factory($this->period);
         return $cron->getNextRunDate($this->date_started)->format('Y-m-d H:i:s');
     }
     return NULL;
 }
Exemple #26
0
 /**
  * Check if it's time to launch cron
  * @return boolean
  */
 public function isDue()
 {
     //check if already sent on that minute
     $last = strtotime($this->getLastRun());
     $now = time();
     $now = $now - $now % 60;
     $last = $last - $last % 60;
     if ($now == $last) {
         return false;
     }
     try {
         $c = new Cron\CronExpression($this->getSchedule(), new Cron\FieldFactory());
         try {
             if ($c->isDue()) {
                 return true;
             }
         } catch (Exception $e) {
         }
         try {
             $prev = $c->getPreviousRunDate()->getTimestamp();
         } catch (Exception $e) {
             return false;
         }
         $diff = abs((strtotime('now') - $prev) / 60);
         if (strtotime($this->getLastRun()) < $prev && ($diff <= config::byKey('maxCatchAllow') || config::byKey('maxCatchAllow') == -1)) {
             return true;
         }
     } catch (Exception $e) {
         log::add('cron', 'debug', 'Error on isDue : ' . $e->getMessage() . ', cron : ' . $this->getSchedule());
     }
     return false;
 }
Exemple #27
0
    $shellCmd = 'crontab -l | grep ' . BASE_URL . FILE_APP . '?MODULE=auto';
    //echo $shellCmd;
    $jobSearch = shell_exec($shellCmd);
    if ($jobSearch == '') {
        $job = '* * * * * curl ' . BASE_URL . FILE_APP . '?MODULE=auto &>/dev/null' . PHP_EOL;
        $output = shell_exec('crontab -l');
        $tmpFile = TMP_UPLOAD_DIR . 'crontab.txt';
        file_put_contents($tmpFile, $output . PHP_EOL . $job . PHP_EOL);
        echo exec('crontab ' . $tmpFile);
        //unlink ($tmpFile);
        echo "No cronjob found for APP " . FILE_APP;
        echo "\n<br />\n";
        echo "Added job: " . $job;
    }
    //TODO: Mejora: Quiza habría que comprobar de algun modop si la llamada procede del cron (quiza mediante useragent curl),
    //para evitar que se repitan tareas si se llama a auto manualmente.
    if (defined('ARR_CRON_JOBS')) {
        foreach (unserialize(ARR_CRON_JOBS) as $nombreJob => $arrDatosJob) {
            if ($arrDatosJob['activado']) {
                $cronExpr = $arrDatosJob['minuto'] . ' ' . $arrDatosJob['hora'] . ' ' . $arrDatosJob['diaMes'] . ' ' . $arrDatosJob['mes'] . ' ' . $arrDatosJob['diaSemana'];
                $cron = Cron\CronExpression::factory($cronExpr);
                if ($cron->isDue()) {
                    eval($arrDatosJob['comando']);
                }
            }
        }
    }
} catch (Exception $e) {
    $infoExc = "Excepcion de tipo: " . get_class($e) . ". Mensaje: " . $e->getMessage() . " en fichero " . $e->getFile() . " en linea " . $e->getLine();
    mail(DEBUG_EMAIL, SITE_NAME . ". AUTO.PHP", $infoExc . "\n\n--\n\n" . $e->getTraceAsString() . "\n\n--\n\n" . print_r($GLOBALS, true));
}
Exemple #28
0
 public function isDue()
 {
     $last = strtotime($this->getLastLaunch());
     $now = time();
     $now = $now - $now % 60;
     $last = $last - $last % 60;
     if ($now == $last) {
         return false;
     }
     if (is_array($this->getSchedule())) {
         foreach ($this->getSchedule() as $schedule) {
             try {
                 $c = new Cron\CronExpression($schedule, new Cron\FieldFactory());
                 try {
                     if ($c->isDue()) {
                         return true;
                     }
                 } catch (Exception $e) {
                 }
                 try {
                     $prev = $c->getPreviousRunDate()->getTimestamp();
                 } catch (Exception $e) {
                     return false;
                 }
                 $lastCheck = strtotime($this->getLastLaunch());
                 $diff = abs((strtotime('now') - $prev) / 60);
                 if ($lastCheck <= $prev && $diff <= config::byKey('maxCatchAllow') || config::byKey('maxCatchAllow') == -1) {
                     return true;
                 }
             } catch (Exception $e) {
             }
         }
     } else {
         try {
             $c = new Cron\CronExpression($this->getSchedule(), new Cron\FieldFactory());
             try {
                 if ($c->isDue()) {
                     return true;
                 }
             } catch (Exception $e) {
             }
             try {
                 $prev = $c->getPreviousRunDate()->getTimestamp();
             } catch (Exception $e) {
                 return false;
             }
             $lastCheck = strtotime($this->getLastLaunch());
             $diff = abs((strtotime('now') - $prev) / 60);
             if ($lastCheck <= $prev && $diff <= config::byKey('maxCatchAllow') || config::byKey('maxCatchAllow') == -1) {
                 return true;
             }
         } catch (Exception $exc) {
         }
     }
     return false;
 }
Exemple #29
0
 public static function cron()
 {
     //Rafraichissement des valeurs des modules
     foreach (eqLogic::byType('zwave') as $eqLogic) {
         if ($eqLogic->getIsEnable() == 1) {
             $scheduler = $eqLogic->getConfiguration('refreshDelay', '');
             if ($scheduler != '') {
                 try {
                     $c = new Cron\CronExpression($scheduler, new Cron\FieldFactory());
                     if ($c->isDue()) {
                         try {
                             foreach ($eqLogic->getCmd('info') as $cmd) {
                                 if ($cmd->getConfiguration('doNotAutoRefresh', 0) == 0) {
                                     $cmd->forceUpdate();
                                 }
                             }
                         } catch (Exception $exc) {
                             log::add('zwave', 'error', __('Erreur pour ', __FILE__) . $eqLogic->getHumanName() . ' : ' . $exc->getMessage());
                         }
                     }
                 } catch (Exception $exc) {
                     log::add('zwave', 'error', __('Expression cron non valide pour ', __FILE__) . $eqLogic->getHumanName() . ' : ' . $scheduler);
                 }
             }
         }
     }
     if (config::byKey('jeeNetwork::mode') == 'slave') {
         $cron = cron::byClassAndFunction('zwave', 'pull');
         if (is_object($cron)) {
             $cron->remove();
         }
     }
 }
 public function getEditForm($id = null, $fields = null)
 {
     $form = parent::getEditForm($id, $fields);
     $task = new DevTaskRunnerCronTask();
     $cron = Cron\CronExpression::factory($task->getSchedule());
     $nextRun = $cron->getNextRunDate()->format('Y-m-d H:i:s');
     $form->Fields()->unshift(LiteralField::create('NextRunMessage', '<p class="message">Next run at ' . $nextRun . '</p>'));
     return $form;
 }