/**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (null === $value) {
         return;
     }
     if (!Validator::isValidExpression($value)) {
         $this->context->buildViolation($constraint->message)->setParameter('{{string}}', $value)->addViolation();
     }
 }
示例#2
0
 /**
  * @param string $expression Cron expression
  *
  * @return int Cache lifetime in seconds
  */
 protected function getCacheLifetimeForExpression($expression)
 {
     if (!CronExpression::isValidExpression($expression)) {
         return 0;
     }
     $now = new \DateTime();
     $cronExpression = CronExpression::factory($expression);
     $endTime = $cronExpression->getNextRunDate($now);
     return $endTime->getTimestamp() - $now->getTimestamp();
 }
 /**
  * @covers Cron\CronExpression::__construct
  * @covers Cron\CronExpression::factory
  * @covers Cron\CronExpression::isValidExpression
  * @covers Cron\CronExpression::setExpression
  * @covers Cron\CronExpression::setPart
  */
 public function testValidationWorks()
 {
     // Invalid. Only four values
     $this->assertFalse(CronExpression::isValidExpression('* * * 1'));
     // Valid
     $this->assertTrue(CronExpression::isValidExpression('* * * * 1'));
 }
示例#4
0
文件: Swoole.php 项目: millken/ypf
 public function crontabWorker()
 {
     $cron_queue = $this->shm->get("worker_cron_queue");
     $cron_ready = $this->shm->get("worker_cron_ready");
     if (empty($cron_queue)) {
         return;
     }
     foreach ($cron_queue as $worker_name => $config) {
         $crontab = \Cron\CronExpression::isValidExpression($config["crontab"]);
         if (!$crontab) {
             $timeNs = intval($config["crontab"]);
         } else {
             $cron = \Cron\CronExpression::factory($config["crontab"]);
             $nextRunTime = $cron->getNextRunDate()->getTimestamp();
             $timeNs = intval($nextRunTime - time());
         }
         if ($timeNs < 1) {
             continue;
         }
         swoole_timer_after(1000 * $timeNs, function () use($worker_name, $config) {
             self::getInstance()->disPatch($config['action'], array('worker_name' => $worker_name));
             $cron_queue = $this->shm->get("worker_cron_queue");
             $cron_ready = $this->shm->get("worker_cron_ready");
             unset($cron_ready[$worker_name]);
             $cron_queue[$worker_name] = $config;
             $this->shm->set("worker_cron_queue", $cron_queue);
             $this->shm->set("worker_cron_ready", $cron_ready);
         });
         unset($cron_queue[$worker_name]);
         $cron_ready[$worker_name] = $config;
     }
     $this->shm->set("worker_cron_queue", $cron_queue);
     $this->shm->set("worker_cron_ready", $cron_ready);
 }
示例#5
0
 /**
  * Função createUpdateJob
  *
  * Creates a new job in the database, if the parameter \$jobID is filled, the Job's content will be updated.
  *
  * @author Henrique Ramos <*****@*****.**>
  * @version 0.2.0
  * @since 0.1.0
  *
  * @param array[] $params F3 parameters array.
  *
  * @throws Exception If _POST parameters job_name, job_cron, job_type, job_path aren't filled or are invalid
  * @throws Exception If can't add the Job in the database
  *
  * @return array[]
  */
 public function createUpdateJob($params)
 {
     global $connectDB, $logger;
     try {
         $jobID = (!empty($params['jobID']) and is_numeric($params['jobID'])) ? $params['jobID'] : NULL;
         $job_author = 1;
         //Melhorar isso
         if (empty($_POST['job_name'])) {
             throw new \Exception(__("You need a valid name for this job."));
         }
         if (empty($_POST['job_cron'])) {
             throw new \Exception(__("We need the Cron filled."));
         }
         if (!\Cron\CronExpression::isValidExpression($_POST['job_cron'])) {
             throw new \Exception(__("We need a valid Cron syntax."));
         }
         if (empty($_POST['job_type']) or !in_array($_POST['job_type'], array('internal', 'external'))) {
             throw new \Exception(__("We need the job type filled.  Choose between \"internal\" and \"external\"."));
         }
         if (empty($_POST['job_path'])) {
             throw new \Exception(__("We need the job path filled."));
         }
         if (empty($_POST['job_status']) or !in_array($_POST['job_status'], array('active', 'disable'))) {
             throw new \Exception(__("We need the job type filled.  Choose between \"active\" and \"disable\"."));
         }
         $alertArray = $_POST['alerts'];
         if (!empty($alertArray) and !is_array($alertArray)) {
             throw new \Exception(__("Fill the \"alerts\" parameter correctly."));
         }
         $job_comment = !empty($_POST['job_comment']) ? $_POST['job_comment'] : NULL;
         $job_status = $_POST['job_status'] == 'active' ? 1 : 0;
         $job_cron = $_POST['job_cron'];
         $job_group = 1;
         //Groups::checkIfGroupExists($_POST['job_group'])?$_POST['job_group']:NULL;
         $timestamp = time();
         $connectDB->beginTransaction();
         $insertJobDatabase = $connectDB->prepare("INSERT INTO `jobs`(`job_id`, `job_name`, `job_date`, `job_cron`, `job_path`, `job_type`, `job_author`, `job_status`, `job_comment`, `job_group`, `is_running`) VALUES (:job_id,:job_name, FROM_UNIXTIME(:job_date),:job_cron,:job_path,:job_type,:job_author,:job_status,:job_comment,:job_group,0) ON DUPLICATE KEY UPDATE `job_name`=:job_name, `job_cron`=:job_cron, `job_path`=:job_path, `job_type`=:job_type, `job_status`=:job_status, `job_comment`=:job_comment, `job_group`=:job_group");
         $insertJobDatabase->bindValue(":job_id", $jobID, \PDO::PARAM_STR);
         $insertJobDatabase->bindValue(":job_name", $_POST['job_name'], \PDO::PARAM_STR);
         $insertJobDatabase->bindValue(":job_date", $timestamp, \PDO::PARAM_INT);
         $insertJobDatabase->bindValue(":job_cron", $job_cron, \PDO::PARAM_STR);
         $insertJobDatabase->bindValue(":job_path", $_POST['job_path'], \PDO::PARAM_STR);
         $insertJobDatabase->bindValue(":job_type", $_POST['job_type'], \PDO::PARAM_STR);
         $insertJobDatabase->bindValue(":job_author", $job_author, \PDO::PARAM_INT);
         $insertJobDatabase->bindValue(":job_status", $job_status, \PDO::PARAM_STR);
         $insertJobDatabase->bindValue(":job_comment", $job_comment, \PDO::PARAM_STR);
         $insertJobDatabase->bindValue(":job_group", $job_group, \PDO::PARAM_STR);
         if (!$insertJobDatabase->execute()) {
             $logger->addError(sprintf(__("MySQL Error %s"), var_Export($insertJobDatabase->errorInfo(), true)));
             throw new \Exception(sprintf(__("Problems with database insertion. Try again later. MySQL Error %s"), $insertJobDatabase->errorCode()));
         }
         $JobIDInfo = $connectDB->lastInsertId();
         foreach ($alertArray as $alertIndividual) {
             $alert = new Alert();
             $alert->addUpdateAlert($JobIDInfo, $alertIndividual);
         }
         $logger->addError(sprintf(__("About Job: {id: \"%s\" name: \"%s\", timestamp: \"%s\", path: \"%s\"}"), $JobIDInfo, $_POST['job_name'], $timestamp, $_POST['job_path']));
         //Inserir no crontab
         switch ($_POST['job_type']) {
             case 'external':
                 $logger->addInfo(sprintf(__("External Job %s"), ExternalCrawlerPath));
                 $pathToCallingJob = ExternalCrawlerPath;
                 break;
             case 'internal':
             default:
                 $logger->addInfo(sprintf(__("Internal Job %s"), InternalCrawlerPath));
                 $pathToCallingJob = InternalCrawlerPath;
                 break;
         }
         $logger->addInfo(sprintf(__("Job Info %s"), var_export($JobInfo, true)));
         $logger->addInfo(sprintf(__("CRON Expression %s"), $job_cron));
         $logger->addInfo(sprintf(__("CRON Log %s"), Zeus_Monitor_Log_Path));
         $logger->addInfo(sprintf(__("Path to call job %s"), $pathToCallingJob));
         $cronParser = \Cron\CronExpression::factory($job_cron);
         $cronMinute = !empty($cronParser->getExpression(1)) ? $cronParser->getExpression(1) : "*";
         $cronHour = !empty($cronParser->getExpression(2)) ? $cronParser->getExpression(2) : "*";
         $cronDayMonth = !empty($cronParser->getExpression(3)) ? $cronParser->getExpression(3) : "*";
         $cronMonth = !empty($cronParser->getExpression(4)) ? $cronParser->getExpression(4) : "*";
         $cronDayWeek = !empty($cronParser->getExpression(5)) ? $cronParser->getExpression(5) : "*";
         $addToCron = new \MyBuilder\Cronos\Formatter\Cron();
         $addToCron->comment(sprintf("Job %s", addslashes(htmlspecialchars($_POST['job_name']))))->job("php {$pathToCallingJob} {$JobIDInfo}")->setMinute($cronMinute)->setHour($cronHour)->setDayOfMonth($cronDayMonth)->setMonth($cronMonth)->setDayOfWeek($cronDayWeek)->setStandardOutFile('log')->appendStandardErrorToFile(Zeus_Monitor_Log_Path)->end();
         $connectDB->commit();
         if (is_null($jobID)) {
             return json_encode(array('success' => sprintf(__("Job inserted with success.<br />Please, insert this code inside your cron:<br /><code>%s</code>"), nl2br($addToCron->format()))));
         }
         return json_encode(array('success' => sprintf(__("Job updated with success.<br />Please, insert this code inside your cron:<br /><code>%s</code>"), nl2br($addToCron->format()))));
     } catch (Exception $e) {
         $connectDB->rollBack();
         throw $e;
     }
 }
示例#6
0
 /**
  * @param string $expression
  * @throws CronomJobException
  */
 private function validateExpression($expression)
 {
     if (!CronExpression::isValidExpression($expression)) {
         $this->throwException('Invalid expression');
     }
 }
示例#7
0
 /**
  * Puts a command into recursive schduled task, this will be enqueued by
  * cron spawned workers for the next single process.
  *
  * @param {string} $name Unique identifier for this schdule task.
  * @param {string} $expr Cron expression for the schdule.
  * @param {string} $command The command to run.
  * @param {?array} $options This is identical to the option array in enqueue()
  *                          but also includes properties starts with dollar sign.
  */
 public static function schedule($name, $expr, $command, $options = array())
 {
     $schedules = Node::get(array(Node::FIELD_COLLECTION => FRAMEWORK_COLLECTION_PROCESS_SCHEDULE, 'name' => $name));
     if ($schedules) {
         throw new ProcessException('Schedule with the same name already exists.', self::ERR_ENQUE);
     }
     if (!CronExpression::isValidExpression($expr)) {
         throw new ProcessException('Expression is not in valid cron format.', self::ERR_CEXPR);
     }
     return Node::set(array(Node::FIELD_COLLECTION => FRAMEWORK_COLLECTION_PROCESS_SCHEDULE, 'name' => $name, 'schedule' => $expr, 'command' => $command) + $options);
 }