本文整理汇总了PHP中Cron\CronExpression类的典型用法代码示例。如果您正苦于以下问题:PHP CronExpression类的具体用法?PHP CronExpression怎么用?PHP CronExpression使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CronExpression类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testIsDueHandlesDifferentDates
/**
* @covers Cron\CronExpression::isDue
*/
public function testIsDueHandlesDifferentDates()
{
$cron = new CronExpression('* * * * *');
$this->assertTrue($cron->isDue());
$this->assertTrue($cron->isDue('now'));
$this->assertTrue($cron->isDue(new \DateTime('now')));
$this->assertTrue($cron->isDue(date('Y-m-d H:i')));
}
示例2: checkSchedule
public function checkSchedule()
{
$timestamp = microtime(true);
$hour = date('G');
if (is_numeric($this->schedule)) {
//If you need to perform at intervals, then check to see whether early to perform
if (isset($this->previousTime) && $timestamp <= $this->previousTime + $this->schedule) {
return;
}
$this->previousTime = $timestamp;
} else {
if (is_array($this->schedule)) {
if (isset($this->previousTime) && $this->previousTime == $hour || !in_array($hour, $this->schedule)) {
return;
}
$this->previousTime = $hour;
} else {
if (is_string($this->schedule)) {
$nextRunDate = false;
try {
//See https://github.com/mtdowling/cron-expression
if (!isset($this->cronExpression)) {
$this->cronExpression = CronExpression::factory($this->schedule);
}
$nextRunDate = $this->cronExpression->getNextRunDate();
} catch (\Exception $e) {
$this->terminate();
}
//first step always skipped
if (!isset($this->previousTime)) {
$this->previousTime = $nextRunDate;
}
if ($this->previousTime == $nextRunDate) {
return;
}
$this->previousTime = $nextRunDate;
} else {
//once
if (isset($this->previousTime)) {
return;
}
$this->previousTime = true;
}
}
}
//execute daemon now
try {
$this->daemon->run();
} catch (\Exception $e) {
$this->terminate();
}
}
示例3: getInterval
public function getInterval()
{
if (null === $this->interval && null !== $this->intervalExpression) {
$this->interval = CronExpression::factory($this->intervalExpression);
}
return parent::getInterval();
}
示例4: __construct
public function __construct($id, $name, $command, $config)
{
$this->id = $id;
$this->name = $name;
$this->config = $config;
if (is_string($command)) {
// Command line string.
$this->command = $command;
} elseif ($command instanceof \Closure) {
// Closure code.
$this->command = $command;
} elseif (is_array($command)) {
// array
if (isset($command["command"])) {
$this->command = $command["command"];
}
if (isset($command["cron_time"])) {
$this->cronTime = $command["cron_time"];
}
if (isset($command["max_processes"])) {
$this->maxProcesses = $command["max_processes"];
} else {
$this->maxProcesses = false;
}
} else {
throw new \InvalidArgumentException("Unsupported type of 'command'.");
}
if ($this->cronTime) {
$this->cronExpression = CronExpression::factory($this->cronTime);
}
}
示例5: indexAction
/**
* @Route("/index/")
* @Template()
*/
public function indexAction(Request $request)
{
$user = $this->get('user')->getCurrentUser();
if (!$user->hasPermission('plugin_ingest_settings')) {
return $this->redirect($this->generateUrl('newscoop_ingestplugin_entry_list'));
}
$em = $this->get('em');
$translator = $this->get('translator');
$ingestCron = $em->getRepository('Newscoop\\Entity\\CronJob')->findOneByName(self::INGEST_CRON_NAME);
$defaultData = array('cron_custom' => $ingestCron->getSchedule());
$form = $this->createFormBuilder($defaultData)->add('cron_custom', 'text', array('label' => 'plugin.ingest.settings.form.label.cron_custom', 'required' => true, 'attr' => array('help_text' => 'plugin.ingest.settings.form.help_text.cron_custom')))->add('save', 'submit', array('label' => 'plugin.ingest.settings.form.label.submit'))->getForm();
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
// Add cornjob stuff
if (array_key_exists('cron_custom', $data) && $data['cron_custom']) {
$cronString = $data['cron_custom'];
try {
$cronExpression = \Cron\CronExpression::factory($cronString);
$ingestCron->setSchedule($cronString);
$em->persist($ingestCron);
} catch (\Exception $e) {
$form->get('cron_custom')->addError(new FormError($e->getMessage()));
}
$em->flush();
}
$this->get('session')->getFlashBag()->add('notice', $translator->trans('plugin.ingest.settings.status.success'));
}
}
return array('form' => $form->createView());
}
示例6: execute
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>Start : ' . ($this->dumpMode ? 'Dump' : 'Execute') . ' all scheduled command</info>');
// Before continue, we check that the output file is valid and writable (except for gaufrette)
if (false !== $this->logPath && strpos($this->logPath, 'gaufrette:') !== 0 && false === is_writable($this->logPath)) {
$output->writeln('<error>' . $this->logPath . ' not found or not writable. You should override `log_path` in your config.yml' . '</error>');
return;
}
$commands = $this->em->getRepository('JMoseCommandSchedulerBundle:ScheduledCommand')->findEnabledCommand();
$noneExecution = true;
foreach ($commands as $command) {
/** @var ScheduledCommand $command */
$cron = CronExpression::factory($command->getCronExpression());
$nextRunDate = $cron->getNextRunDate($command->getLastExecution());
$now = new \DateTime();
if ($command->isExecuteImmediately()) {
$noneExecution = false;
$output->writeln('Immediately execution asked for : <comment>' . $command->getCommand() . '</comment>');
if (!$input->getOption('dump')) {
$this->executeCommand($command, $output, $input);
}
} elseif ($nextRunDate < $now) {
$noneExecution = false;
$output->writeln('Command <comment>' . $command->getCommand() . '</comment> should be executed - last execution : <comment>' . $command->getLastExecution()->format('d/m/Y H:i:s') . '.</comment>');
if (!$input->getOption('dump')) {
$this->executeCommand($command, $output, $input);
}
}
}
if (true === $noneExecution) {
$output->writeln('Nothing to do.');
}
}
示例7: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$dryRun = $input->getOption('dry-run');
$content = $this->processConfig($this->crontab);
$enviroment = isset($content['env']) ? $content['env'] : array();
$commands = isset($content['commands']) ? $content['commands'] : array();
foreach ($commands as $entry) {
preg_match('/\\[(.*)\\](.*)/', $entry, $match);
$tab = $match[1];
$command = $match[2];
$cron = CronExpression::factory($tab);
$output->writeLn('<info>- Checking schedule entry: ' . $tab . '</info>');
// If the cron is not due for execution, just skip
if (!$cron->isDue()) {
continue;
}
// Construct the fork command
$fork = $command . " > " . $this->log . " 2>&1 & echo \$!";
$output->writeLn('<info>- Command:</info> ' . $fork);
// Start a new process
if (!$dryRun) {
exec($fork, $pid);
$pid = current($pid);
$output->writeLn('<info>- Process created:</info> ' . $pid);
} else {
$output->writeLn('<info>- Skipping execution (--dry-run)</info>');
}
}
}
示例8: addTriggerNodes
/**
* @param ArrayNodeDefinition $nodeDefinition
* @return ArrayNodeDefinition
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function addTriggerNodes(ArrayNodeDefinition $nodeDefinition)
{
$nodeDefinition->children()->enumNode('event')->defaultNull()->values(ProcessTrigger::getAllowedEvents())->end()->scalarNode('field')->defaultNull()->end()->integerNode('priority')->defaultValue(Job::PRIORITY_DEFAULT)->end()->booleanNode('queued')->defaultFalse()->end()->scalarNode('time_shift')->defaultNull()->validate()->always(function ($value) {
// if value is an integer value
$integerValue = filter_var($value, FILTER_VALIDATE_INT);
if (false !== $integerValue) {
return $integerValue;
}
// if value is DateInterval spec
try {
return ProcessTrigger::convertDateIntervalToSeconds(new \DateInterval($value));
} catch (\Exception $e) {
throw new \LogicException(sprintf('Time shift "%s" is not compatible with DateInterval', $value));
}
})->end()->end()->scalarNode('cron')->defaultNull()->validate()->always(function ($value) {
if ($value !== null) {
// validate expression string
CronExpression::factory($value);
}
return $value;
})->end()->end()->end()->validate()->always(function ($data) {
if ($data['event'] && $data['cron']) {
throw new \LogicException('Only one child node "event" or "cron" must be configured.');
}
if ($data['cron'] && ($data['field'] || $data['queued'] || $data['time_shift'])) {
throw new \LogicException('Nodes "field", "queued" and "time_shift" are only allowed with event node.');
}
if ($data['field'] && $data['event'] !== ProcessTrigger::EVENT_UPDATE) {
throw new \LogicException('Field is only allowed for update event');
}
return $data;
})->end();
return $nodeDefinition;
}
示例9: addRepeatedJob
public function addRepeatedJob(Job $job, $cronString, $enabled = true, $lockType = false)
{
// This will validate the string
CronExpression::factory($cronString);
$this->commandExecutor->execute(new PushRepeatedJob($this->id, $job, $lockType, $cronString, $enabled));
return $job;
}
示例10: parse
/**
* 解析crontab的定时格式,linux只支持到分钟/,这个类支持到秒
* @param string $crontab_string :
*
* 0 1 2 3 4 5
* * * * * * *
* - - - - - -
* | | | | | |
* | | | | | +----- day of week (0 - 6) (Sunday=0)
* | | | | +----- month (1 - 12)
* | | | +------- day of month (1 - 31)
* | | +--------- hour (0 - 23)
* | +----------- min (0 - 59)
* +------------- sec (0-59)
* @param int $start_time timestamp [default=current timestamp]
* @return int unix timestamp - 下一分钟内执行是否需要执行任务,如果需要,则把需要在那几秒执行返回
* @throws InvalidArgumentException 错误信息
*/
public static function parse($crontab_string, $start_time = null)
{
if (!preg_match('/^((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)$/i', trim($crontab_string))) {
if (!preg_match('/^((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)\\s+((\\*(\\/[0-9]+)?)|[0-9\\-\\,\\/]+)$/i', trim($crontab_string))) {
self::$error = "Invalid cron string: " . $crontab_string;
return false;
}
}
if ($start_time && !is_numeric($start_time)) {
self::$error = "\$start_time must be a valid unix timestamp ({$start_time} given)";
return false;
}
$cron = preg_split("/[\\s]+/i", trim($crontab_string));
$start = empty($start_time) ? time() : $start_time;
if (count($cron) == 5) {
$date = array('second' => array(1 => 1), 'minutes' => self::_parse_cron_number($cron[0], 0, 59), 'hours' => self::_parse_cron_number($cron[1], 0, 23), 'day' => self::_parse_cron_number($cron[2], 1, 31), 'month' => self::_parse_cron_number($cron[3], 1, 12), 'week' => self::_parse_cron_number($cron[4], 0, 6));
$cron = \Cron\CronExpression::factory($cron[0] . ' ' . $cron[1] . ' ' . $cron[2] . ' ' . $cron[3] . ' ' . $cron[4] . ' *');
}
if (in_array(intval(date('i', $start)), $date['minutes']) && in_array(intval(date('G', $start)), $date['hours']) && in_array(intval(date('j', $start)), $date['day']) && in_array(intval(date('w', $start)), $date['week']) && in_array(intval(date('n', $start)), $date['month'])) {
$preDate = $cron->getPreviousRunDate()->format('Y-m-d H:i:s');
$Nextdate = $cron->getNextRunDate()->format('Y-m-d H:i:s');
return (strtotime($Nextdate) - $start + ($start - strtotime($preDate))) / 2;
}
return null;
}
示例11: testExecuteWithFail
public function testExecuteWithFail()
{
$singleTask = $this->createTask('Test workload 1', null, FailTestHandler::class);
$laterTask = $this->createTask('Test workload 2', null, FailTestHandler::class);
$intervalTask = $this->createTask('Test workload 3', CronExpression::factory('@daily'), FailTestHandler::class);
/** @var TaskExecutionInterface[] $executions */
$executions = [$this->createTaskExecution($singleTask, new \DateTime('-1 hour')), $this->createTaskExecution($laterTask, new \DateTime('+1 hour')), $this->createTaskExecution($intervalTask, new \DateTime('-2 hour'))];
$this->commandTester->execute(['command' => $this->command->getName()]);
$this->assertEquals(TaskStatus::FAILED, $executions[0]->getStatus());
$this->assertNull($executions[0]->getResult());
$this->assertGreaterThan(0, $executions[0]->getDuration());
$this->assertGreaterThanOrEqual($executions[0]->getStartTime(), $executions[0]->getEndTime());
$this->assertEquals(TaskStatus::PLANNED, $executions[1]->getStatus());
$this->assertNull($executions[1]->getResult());
$this->assertNull($executions[1]->getDuration());
$this->assertNull($executions[1]->getStartTime());
$this->assertNull($executions[1]->getEndTime());
$this->assertEquals(TaskStatus::FAILED, $executions[2]->getStatus());
$this->assertNull($executions[2]->getResult());
$this->assertGreaterThan(0, $executions[2]->getDuration());
$this->assertGreaterThanOrEqual($executions[2]->getStartTime(), $executions[2]->getEndTime());
$result = $this->taskExecutionRepository->findAll(2, 3);
$this->assertCount(1, $result);
$this->assertEquals($intervalTask, $result[0]->getTask());
$this->assertEquals(TaskStatus::PLANNED, $result[0]->getStatus());
$this->assertEquals(FailTestHandler::class, $result[0]->getHandlerClass());
$this->assertEquals('Test workload 3', $result[0]->getWorkload());
}
示例12: isDue
/**
* @param string $schedule
* @return bool
*/
public function isDue($schedule)
{
$dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', $schedule);
if ($dateTime !== false) {
return $dateTime->format('Y-m-d H:i') == date('Y-m-d H:i');
}
return CronExpression::factory((string) $schedule)->isDue();
}
示例13: __construct
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->model->is_repeating_task = false;
$this->model->cron_expression = '* * * * *';
$this->model->status = DeferredQueue::STATUS_SCHEDULED;
$cron = CronExpression::factory($this->model->cron_expression);
$this->model->next_start = date('Y-m-d H:i:s', $cron->getNextRunDate()->getTimestamp());
}
示例14: startDueJobs
/**
* Start Due Jobs
*/
public function startDueJobs($current_time = null)
{
foreach ($this->jobs as $job) {
$schedule = CronExpression::factory($job->schedule);
if ($schedule->isDue($current_time)) {
$this->schedule->run($job);
}
}
}
示例15: isDue
/**
* Checks whether the task is currently due
* @return bool
*/
public function isDue()
{
$expression = $this->getExpression();
if (!$expression) {
return false;
}
$cron = \Cron\CronExpression::factory($expression);
return $cron->isDue();
}