/** * 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)); }
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); } } }
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; } }
protected function getCronExpression($line) { $cronLine = ""; try { $cronLine = Cron\CronExpression::factory($this->getDateTime($line)); } catch (Exception $e) { } return $cronLine; }
/** * 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')); } } }
/** * 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; }
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; }
public function run() { if (in_array($_SERVER["REMOTE_ADDR"], $this->config["ACCEPTED_IPS"])) { // not very secure - but worst case they fire off the run early if (!file_exists("/tmp/kritbot")) { touch("/tmp/kritbot"); try { /** @var \application\models\Jobs[] $jobs */ $jobs = DB::fetchObject("SELECT * FROM jobs", "\\application\\models\\Jobs"); foreach ($jobs as $job) { if ($job->runType == 1) { $cron = Cron\CronExpression::factory($job->cron); if ($cron->isDue() || $job->force_run == 1) { $output = []; $returnVar = 0; $jobName = isset($job->jobName) && !empty($job->jobName) && $job->jobName ? $job->jobName : "----NOT-SET----"; $dir = __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "tmp" . DIRECTORY_SEPARATOR . $jobName; if (is_dir($dir)) { $this->rrmdir($dir . DIRECTORY_SEPARATOR); mkdir($dir, 0777, true); } else { mkdir($dir, 0777, true); } $start = microtime(true); // grumble grumble something something windows if (stripos(php_uname("s"), "Win") !== false) { file_put_contents("{$dir}/kritscript.bat", $job->runScript); exec("c:\\windows\\system32\\cmd.exe /c {$dir}\\kritscript.bat", $output, $returnVar); } else { file_put_contents("{$dir}/kritscript", $job->runScript); chmod("{$dir}/kritscript", 0777); exec("{$dir}/kritscript", $output, $returnVar); } $end = microtime(true); $delta = $end - $start; $scriptOutput = implode("\n", $output); if ($returnVar != 0) { if (stripos(php_uname("s"), "Win") !== false) { file_put_contents("{$dir}/failkritscript.bat", $job->failScript); exec("c:\\windows\\system32\\cmd.exe /c {$dir}\failkirtscript.bat"); } else { file_put_contents("{$dir}/failkritscript", $job->failScript); chmod("{$dir}/failkritscript", 0777); exec("{$dir}/failkritscript", $output, $returnVar); } } $historyObj = new \application\models\Histories(); $historyObj->output = $scriptOutput; $historyObj->result = $returnVar; $historyObj->time_taken = $delta; $historyObj->jobs_id = $job->id; $now = date("Y-m-d H:i:s"); $historyObj->run_date = $now; $historyObj->save(); $job->force_run = 0; $job->last_run = $now; $job->last_result = $returnVar; $job->save(); } } } unlink("/tmp/kritbot"); } catch (\Exception $e) { unlink("/tmp/kritbot"); } } } }
<?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();
private function runjobs() { if (!$this->storePath) { $this->storePath = TMP; } // look for a store of the previous run $store = ""; $storeFilePath = $this->storePath . $this->storeFile; if (file_exists($storeFilePath)) { $store = file_get_contents($storeFilePath); } $this->out(date(DATE_SQL) . ' Reading from: ' . $storeFilePath); // build or rebuild the store if ($store != '') { $store = json_decode($store, true); } else { $store = $this->schedule; } App::import('Vendor', 'Fork', array('file' => 'duncan3dc/fork-helper/src/Fork.php')); $fork = new \duncan3dc\Helpers\Fork(); //debug($this->schedule); //debug($store); // run the jobs that need to be run, record the time foreach ($this->schedule as $name => $job) { $now = new DateTime(); $task = $job['task']; $action = $job['action']; // if the job has never been run before, create it if (!isset($store[$name])) { $store[$name] = $job; } // figure out the last run date $tmptime = $store[$name]['lastRun']; if ($tmptime == null) { $tmptime = new DateTime("1969-01-01 00:00:00"); } elseif (is_array($tmptime)) { $tmptime = new DateTime($tmptime['date'], new DateTimeZone($tmptime['timezone'])); } elseif (is_string($tmptime)) { $tmptime = new DateTime($tmptime); } $runNow = false; // determine the next run time based on the last if (substr($job['interval'], 0, 1) === 'P') { $tmptime->add(new DateInterval($job['interval'])); // "P10DT4H" http://www.php.net/manual/en/class.dateinterval.php $runNow = $tmptime <= $now; } elseif (strtotime($job['interval']) !== false) { $tmptime->modify($job['interval']); // "next day 10:30" http://www.php.net/manual/en/datetime.formats.relative.php $runNow = $tmptime <= $now; } else { //cron expression //https://github.com/mtdowling/cron-expression $cron = Cron\CronExpression::factory($job['interval']); $runNow = $cron->getNextRunDate($tmptime) <= $now; $tmptime = $cron->getNextRunDate(); //override for beter log readingz } $this->out('JOB ' . $job['name'] . ' next run time: ' . $tmptime->format(DATE_SQL)); // is it time to run? has it never been run before? //aditionaly, is it currently running if ($runNow && empty($store[$name]['runningPID'])) { $this->out(date(DATE_SQL) . " Running {$name} --------------------------------------- "); if (!isset($this->{$task})) { $this->{$task} = $this->Tasks->load($task); // load models if they aren't already foreach ($this->{$task}->uses as $mk => $mv) { if (!isset($this->{$task}->{$mv})) { App::uses('AppModel', 'Model'); App::uses($mv, 'Model'); $this->{$task}->{$mv} = new $mv(); } } } // grab the entire schedule record incase it was updated.. $store[$name] = $this->schedule[$name]; // execute the task and store the result //$store[$name]['lastResult'] = call_user_func_array(array($this->$task, $action), $job['args']); //$reportInvoicesTask = $this->Tasks->load('ReportInvoices'); //$fork->call(array($reportInvoicesTask,"execute"),array('2014-01-01 00:00:00','2016-01-01 00:00:00',"invoiceDaily")); //$store[$name]['lastResult'] = $fork->call(array($this->$task, $action), $job['args']); $store[$name]['runningPID'] = $fork->call(array($this->{$task}, $action), $job['args']); $this->out(date(DATE_SQL) . " Started {$name} as PID: " . $store[$name]['runningPID']); $this->activeThreads[] = $store[$name]['runningPID']; //unset($reportInvoicesTask); // assign it the current time $now = new DateTime(); $store[$name]['lastRun'] = $now->format('Y-m-d H:i:s'); } } // write the store back to the file file_put_contents($this->storePath . $this->storeFile, json_encode($store)); $this->out(date(DATE_SQL) . ' All pending tasks are no longer pending'); //$runningProcesses=Hash::extract($store,"{s}.runningPID"); //debug($runningProcesses); for ($pcnt = 0; $pcnt < count($this->activeThreads); $pcnt++) { try { $endedPID = $fork->waitAny(); $store = file_get_contents($storeFilePath); $store = json_decode($store, true); foreach ($store as $v) { if ($v['runningPID'] == $endedPID) { $finishedTask = $v; break; } } $this->out(date(DATE_SQL) . " Ended " . $finishedTask['name'] . " as PID: " . $endedPID); $store[$finishedTask['name']]['runningPID'] = null; file_put_contents($this->storePath . $this->storeFile, json_encode($store)); } catch (Exception $e) { $message = $e->getMessage(); $endedPID = $e->getCode(); $store = file_get_contents($storeFilePath); $store = json_decode($store, true); foreach ($store as $v) { if ($v['runningPID'] == $endedPID) { $finishedTask = $v; break; } } $this->out(date(DATE_SQL) . " Ended " . $finishedTask['name'] . " as PID: " . $endedPID . " with EXCEPTION: \n" . $message); $store[$finishedTask['name']]['runningPID'] = null; $store[$finishedTask['name']]['lastResult'] = $message; file_put_contents($this->storePath . $this->storeFile, json_encode($store)); } } }
use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Crons'; $this->params['breadcrumbs'][] = $this->title; $this->params['topMenuKey'] = 'system'; $this->params['leftMenuKey'] = 'cron'; ?> <div class="cron-index"> <h1><?php echo Html::encode($this->title); ?> </h1> <p> <?php echo Html::a('Create Cron', ['create'], ['class' => 'btn btn-success']); ?> </p> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'columns' => [['class' => 'yii\\grid\\SerialColumn'], 'cron_id', 'name', 'expression', ['label' => 'Next Time', 'value' => function ($model) { $cron = Cron\CronExpression::factory($model->expression); return $cron->getNextRunDate()->format('Y-m-d H:i:s'); }], 'func', 'once', 'status', ['class' => 'yii\\grid\\ActionColumn']]]); ?> </div>
$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)); }
/** * 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; }
/** * 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') . '.'); } }
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; }