private function validateExpression()
 {
     if (!empty($this->cron_expression)) {
         $cronTab = new CronExpression($this->cron_expression, new \Cron\FieldFactory());
         $order = array(5, 3, 2, 4, 1, 0);
         foreach (array_reverse($order) as $position) {
             $this->cron_parts[$position] = $cronTab->getExpression($position);
             if (null === $this->cron_parts[$position] && $position <= 3) {
                 return FALSE;
             }
         }
         return TRUE;
     }
     return FALSE;
 }
Example #2
0
function parseCron($path)
{
    chdir($path);
    $crons = array();
    $files = glob('*');
    foreach ($files as $file) {
        $rows = file($file);
        foreach ($rows as $row) {
            $row = preg_replace("/[ \t]+/", ' ', trim($row, " \t\n"));
            $row = preg_replace("/#.*/", '', $row);
            if ($row) {
                preg_match_all('/(\\S+\\s+){5}|.*/', $row, $matchs);
                if ($matchs[0]) {
                    $cron = array();
                    $cron['schema'] = trim($matchs[0][0]);
                    $cron['command'] = trim($matchs[0][1]);
                    $cron['cron'] = CronExpression::factory($cron['schema']);
                    $cron['time'] = $cron['cron']->getNextRunDate();
                    $crons[] = $cron;
                }
            }
        }
    }
    return $crons;
}
 /**
  * @param string $hook The hook to trigger when this action runs
  * @param array $args Args to pass when the hook is triggered
  * @param int $first Unix timestamp for the first run
  * @param int $schedule A cron definition string
  * @param string $group A group to put the action in
  *
  * @return string The ID of the stored action
  */
 public function cron($hook, $args = array(), $first = NULL, $schedule = NULL, $group = '')
 {
     if (empty($schedule)) {
         return $this->single($hook, $args, $first, $group);
     }
     $date = as_get_datetime_object($first);
     $cron = CronExpression::factory($schedule);
     $schedule = new ActionScheduler_CronSchedule($date, $cron);
     $action = new ActionScheduler_Action($hook, $args, $schedule, $group);
     return $this->store($action);
 }
 public function test_cron_format()
 {
     $time = new DateTime('2014-01-01');
     $cron = CronExpression::factory('0 0 10 10 *');
     $schedule = new ActionScheduler_CronSchedule($time, $cron);
     $this->assertEquals(new DateTime('2014-10-10'), $schedule->next());
     $cron = CronExpression::factory('0 0 L 1/2 *');
     $schedule = new ActionScheduler_CronSchedule($time, $cron);
     $this->assertEquals(new DateTime('2014-01-31'), $schedule->next());
     $this->assertEquals(new DateTime('2014-07-31'), $schedule->next(new DateTime('2014-06-01')));
     $this->assertEquals(new DateTime('2028-11-30'), $schedule->next(new DateTime('2028-11-01')));
     $cron = CronExpression::factory('30 14 * * MON#3 *');
     $schedule = new ActionScheduler_CronSchedule($time, $cron);
     $this->assertEquals(new DateTime('2014-01-20 14:30:00'), $schedule->next());
     $this->assertEquals(new DateTime('2014-05-19 14:30:00'), $schedule->next(new DateTime('2014-05-01')));
 }
Example #5
0
 /**
  * Parse crons.
  * 
  * @param  array    $crons 
  * @access public
  * @return array
  */
 public function parseCron($crons)
 {
     $this->app->loadClass('crontab', true);
     $parsedCron = array();
     foreach ($crons as $cron) {
         $row = "{$cron->m} {$cron->h} {$cron->dom} {$cron->mon} {$cron->dow} {$cron->command}";
         preg_match_all('/(\\S+\\s+){5}|.*/', $row, $matchs);
         if ($matchs[0]) {
             try {
                 $parsedCron = array();
                 $parsedCron['schema'] = trim($matchs[0][0]);
                 $parsedCron['command'] = trim($matchs[0][1]);
                 $parsedCron['cron'] = CronExpression::factory($parsedCron['schema']);
                 $parsedCron['time'] = $parsedCron['cron']->getNextRunDate();
                 $parsedCrons[$cron->id] = $parsedCron;
             } catch (InvalidArgumentException $e) {
                 $this->dao->update(TABLE_CRON)->set('status')->eq('stop')->where('id')->eq($cron->id)->exec();
                 continue;
             }
         }
     }
     $this->dao->update(TABLE_CRON)->set('lastTime')->eq(date(DT_DATETIME1))->where('lastTime')->eq('0000-00-00 00:00:00')->andWhere('status')->ne('stop')->exec();
     return $parsedCrons;
 }
 private function validateSaveTasktemplate4Modify($request, array &$validateInfo)
 {
     /*{{{*/
     $taskTemplate = DAL::get()->find('TaskTemplate', $request->tasktemplateid);
     if ($taskTemplate->queueTemplate->isAnyTime()) {
         /*{{{*/
         if (trim($request->title) != $taskTemplate->getTrueTitle()) {
             $validateInfo['error'][] = '随意队列, 不能修改title';
         }
         if (trim($request->crontimestr) != $taskTemplate->queueTemplate->cronTimeStr) {
             $validateInfo['error'][] = '随意队列, 不能修改时间配置';
         }
     }
     /*}}}*/
     if (CronExpression::isRight(trim($request->crontimestr)) && trim($request->crontimestr) != $taskTemplate->queueTemplate->cronTimeStr) {
         $nextRunDateStr = CronExpression::factory(trim($request->crontimestr))->getNextRunDate()->format('Y-m-d H:i:s');
         $validateInfo['warning'][] = "此脚本下一次运行时间为{$nextRunDateStr}";
     }
     if (trim($request->scriptparams) != '') {
         $paramArr = preg_split('#,\\s*#', $request->scriptparams);
         $cnt = count($paramArr);
         $paramStr = implode('、', $paramArr);
         if ($paramArr != $taskTemplate->scriptParams) {
             $validateInfo['warning'][] = "你输入的{$cnt}个参数分别{$paramStr}";
         }
     }
     if (false == CronExpression::isRight(trim($request->crontimestr))) {
         $validateInfo['error'][] = '时间配置输入有误';
     }
     $this->validateSaveTasktemplate4Common($request, $validateInfo);
 }
 /**
  * @param DateTime $after
  * @return DateTime|null
  */
 public function next(DateTime $after = NULL)
 {
     $after = empty($after) ? clone $this->start : clone $after;
     return $this->cron->getNextRunDate($after, 0, TRUE);
 }
 public function event_scheduler_list_json()
 {
     if ($this->isAjax) {
         if ($no_auth = $this->checkAuth()) {
             return $no_auth;
         }
     }
     $response = array('data' => array(), 'recordsTotal' => 0, 'recordsFiltered' => 0);
     $error = $this->setLocalization("Error");
     $param = !empty($this->data) ? $this->data : array();
     $query_param = $this->prepareDataTableParams($param, array('operations', '_', 'next_run', 'event_trans'));
     if (!isset($query_param['where'])) {
         $query_param['where'] = array();
     }
     $filter = $this->getEventsFilters();
     $query_param['where'] = array_merge($query_param['where'], $filter);
     $filds_for_select = $this->getScheduleEventsFields();
     if (!empty($query_param['select'])) {
         $this->cleanQueryParams($query_param, array_keys($filds_for_select), $filds_for_select);
     } else {
         $query_param['select'] = $filds_for_select;
     }
     if (!array_key_exists('event', $query_param['select'])) {
         $query_param['select']['event'] = $filds_for_select['event'];
     }
     if (!array_key_exists('last_run', $query_param['select'])) {
         $query_param['select']['last_run'] = $filds_for_select['last_run'];
     }
     if (array_key_exists('id', $this->postData)) {
         $query_param['where'] = array('S_E.id' => $this->postData['id']);
         $response['action'] = 'fillModalForm';
     }
     $response['recordsTotal'] = $this->db->getTotalRowsScheduleEvents();
     $response["recordsFiltered"] = $this->db->getTotalRowsScheduleEvents($query_param['where'], $query_param['like']);
     $cronTab = new \CronExpression('* * * * *', new Cron\FieldFactory());
     foreach ($cronTab->getMessageParts() as $key => $val) {
         $cronTab->setMessageParts($key, $this->setLocalization($val));
     }
     $deferred = $this->setLocalization('deferred');
     $unlimited = $this->setLocalization('unlimited');
     $not_run = $this->setLocalization('do not yet running');
     $all_event = array_merge($this->formEvent, $this->hiddenEvent);
     $all_event = array_combine($this->getFieldFromArray($all_event, 'id'), $this->getFieldFromArray($all_event, 'title'));
     $all_recipients = array('to_all' => $this->setLocalization('All'), 'by_group' => $this->setLocalization('Group'), 'to_single' => $this->setLocalization('One'), 'by_filter' => $this->setLocalization('Filter'));
     $response['data'] = array_map(function ($row) use($cronTab, $deferred, $all_event, $all_recipients, $unlimited, $not_run) {
         $cronTab->setCurrentTime($row['last_run']);
         $row['event_trans'] = $all_event[$row['event']];
         $row['post_function'] = array_key_exists($row['post_function'], $all_event) ? $all_event[$row['post_function']] : $row['post_function'];
         $row['date_begin'] = (int) strtotime($row['date_begin']);
         if ($row['date_begin'] < 0) {
             $row['date_begin'] = 0;
         }
         $row['date_end'] = (int) strtotime($row['date_end']);
         if ($row['date_end'] <= 0) {
             $row['date_end'] = $unlimited;
         }
         $row['last_run'] = (int) strtotime($row['last_run']);
         if ($row['last_run'] <= 0) {
             $row['last_run'] = $not_run;
         }
         $row['cron_str'] = $row['schedule'];
         $cronTab->setExpression($row['schedule'])->setMessage();
         if (!empty($row['schedule']) && (int) $row['periodic']) {
             $row['next_run'] = $cronTab->getNextRunDate()->getTimestamp();
             $row['schedule'] = implode(' ', $cronTab->getMessage());
         } else {
             $row['date_end'] = $row['next_run'] = $row['state'] ? $cronTab->getNextRunDate()->getTimestamp() : $deferred;
             $row['schedule'] = $cronTab->getMessageParts('once');
         }
         $recipient = json_decode($row['recipient'], TRUE);
         list($row['recipient'], $recipient) = each($recipient);
         $row['user_list_type'] = $row['recipient'];
         $row['recipient'] = $all_recipients[$row['recipient']];
         if (!empty($recipient) && is_array($recipient)) {
             $row = array_merge($row, (array) $recipient);
         }
         return $row;
     }, $this->db->getScheduleEvents($query_param));
     $response["draw"] = !empty($this->data['draw']) ? $this->data['draw'] : 1;
     $error = '';
     if ($this->isAjax) {
         if (!empty($response['data']) && !empty($this->postData['id'])) {
             $response['data'][0] = array_merge($response['data'][0], array_map(function ($row) {
                 return is_numeric($row) ? str_pad((string) $row, 2, '0', STR_PAD_LEFT) : $row;
             }, \CronForm::getInstance()->setExpression($response['data'][0]['cron_str'])->getFormData()));
             if (array_key_exists('interval', $response['data'][0])) {
                 $response['data'][0]['interval'] = str_replace('0', 'repeating_interval_', $response['data'][0]['interval']);
             }
             $response['data'][0]['type'] = "schedule_type_" . ((int) $response['data'][0]['periodic'] + 1);
         }
         $response = $this->generateAjaxResponse($response);
         return new Response(json_encode($response), empty($error) ? 200 : 500);
     } else {
         return $response;
     }
 }
 /**
  * Tests for known formatting problems
  *
  * @return null
  */
 public function testIssue29()
 {
     $cron = CronExpression::factory('@weekly');
     $this->assertEquals('2013-03-10 00:00:00', $cron->getPreviousRunDate('2013-03-17 00:00:00')->format('Y-m-d H:i:s'));
 }
<?php

require_once __DIR__ . '/../../admin/vendor/autoload.php';
define('PROJECT_PATH', realpath(dirname(__FILE__) . '/../'));
require_once PROJECT_PATH . '/../storage/config.php';
$run_start_time = time();
$five_minute_interval = $run_start_time - $run_start_time % 300 + 300;
echo strftime('%Y-%m-%d %H:%M:%S', $five_minute_interval), PHP_EOL;
$_SERVER['TARGET'] = 'ADM';
$schedule_events = Mysql::getInstance()->from("`schedule_events`")->where(array('state' => 1, 'date_begin<=' => 'now()'))->where(array('date_end>last_run and date_end>' => 'now()', 'date_end' => 0), 'OR ')->get()->all();
$update_data = array();
$event = new \AdminPanelEvents();
$cronTab = new \CronExpression('* * * * *', new Cron\FieldFactory());
$cronTab->setCurrentTime('now');
foreach ($schedule_events as $row) {
    if (!empty($row['schedule'])) {
        $cronTab->setExpression($row['schedule']);
        $next_run_interval = $five_minute_interval - $cronTab->getNextRunDate()->getTimestamp();
        if ($next_run_interval < 0 || $next_run_interval > 300) {
            continue;
        }
        $event->setTtl((int) $row['ttl']);
        if (!empty($row['post_function']) && !empty($row['param1'])) {
            $event->setPostFunctionParam($row['post_function'], $row['param1']);
        } else {
            $event->setPostFunctionParam('', '');
        }
        if ($add_params = json_decode($row['recipient'], TRUE)) {
            list($user_list_type, $param) = each($add_params);
            $row['user_list_type'] = $user_list_type;
            if (is_array($param)) {