Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Data Fields | Protected Member Functions | Protected Attributes
ProcessCronQueueObserver Class Reference
Inheritance diagram for ProcessCronQueueObserver:
ObserverInterface

Public Member Functions

 __construct (\Magento\Framework\ObjectManagerInterface $objectManager, \Magento\Cron\Model\ScheduleFactory $scheduleFactory, \Magento\Framework\App\CacheInterface $cache, \Magento\Cron\Model\ConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Framework\App\Console\Request $request, \Magento\Framework\ShellInterface $shell, \Magento\Framework\Stdlib\DateTime\DateTime $dateTime, \Magento\Framework\Process\PhpExecutableFinderFactory $phpExecutableFinderFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\App\State $state, StatFactory $statFactory, \Magento\Framework\Lock\LockManagerInterface $lockManager)
 
 execute (\Magento\Framework\Event\Observer $observer)
 
- Public Member Functions inherited from ObserverInterface
 execute (Observer $observer)
 

Data Fields

const CACHE_KEY_LAST_SCHEDULE_GENERATE_AT = 'cron_last_schedule_generate_at'
 
const CACHE_KEY_LAST_HISTORY_CLEANUP_AT = 'cron_last_history_cleanup_at'
 
const STANDALONE_PROCESS_STARTED = 'standaloneProcessStarted'
 
const XML_PATH_SCHEDULE_GENERATE_EVERY = 'schedule_generate_every'
 
const XML_PATH_SCHEDULE_AHEAD_FOR = 'schedule_ahead_for'
 
const XML_PATH_SCHEDULE_LIFETIME = 'schedule_lifetime'
 
const XML_PATH_HISTORY_CLEANUP_EVERY = 'history_cleanup_every'
 
const XML_PATH_HISTORY_SUCCESS = 'history_success_lifetime'
 
const XML_PATH_HISTORY_FAILURE = 'history_failure_lifetime'
 
const SECONDS_IN_MINUTE = 60
 
const LOCK_TIMEOUT = 5
 
const LOCK_PREFIX = 'CRON_GROUP_'
 

Protected Member Functions

 _runJob ($scheduledTime, $currentTime, $jobConfig, $schedule, $groupId)
 
 _generateJobs ($jobs, $exists, $groupId)
 
 getConfigSchedule ($jobConfig)
 
 saveSchedule ($jobCode, $cronExpression, $timeInterval, $exists)
 
 createSchedule ($jobCode, $cronExpression, $time)
 
 getScheduleTimeInterval ($groupId)
 

Protected Attributes

 $_pendingSchedules
 
 $_config
 
 $_objectManager
 
 $_cache
 
 $_scopeConfig
 
 $_scheduleFactory
 
 $_request
 
 $_shell
 
 $dateTime
 
 $phpExecutableFinder
 

Detailed Description

The observer for processing cron jobs.

@SuppressWarnings(PHPMD.CouplingBetweenObjects)

Definition at line 24 of file ProcessCronQueueObserver.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( \Magento\Framework\ObjectManagerInterface  $objectManager,
\Magento\Cron\Model\ScheduleFactory  $scheduleFactory,
\Magento\Framework\App\CacheInterface  $cache,
\Magento\Cron\Model\ConfigInterface  $config,
\Magento\Framework\App\Config\ScopeConfigInterface  $scopeConfig,
\Magento\Framework\App\Console\Request  $request,
\Magento\Framework\ShellInterface  $shell,
\Magento\Framework\Stdlib\DateTime\DateTime  $dateTime,
\Magento\Framework\Process\PhpExecutableFinderFactory  $phpExecutableFinderFactory,
\Psr\Log\LoggerInterface  $logger,
\Magento\Framework\App\State  $state,
StatFactory  $statFactory,
\Magento\Framework\Lock\LockManagerInterface  $lockManager 
)
Parameters
\Magento\Framework\ObjectManagerInterface$objectManager
\Magento\Cron\Model\ScheduleFactory$scheduleFactory
\Magento\Framework\App\CacheInterface$cache
\Magento\Cron\Model\ConfigInterface$config
\Magento\Framework\App\Config\ScopeConfigInterface$scopeConfig
\Magento\Framework\App\Console\Request$request
\Magento\Framework\ShellInterface$shell
\Magento\Framework\Stdlib\DateTime\DateTime$dateTime
\Magento\Framework\Process\PhpExecutableFinderFactory$phpExecutableFinderFactory
\Psr\Log\LoggerInterface$logger
State$state
StatFactory$statFactory
\Magento\Framework\Lock\LockManagerInterface$lockManager@SuppressWarnings(PHPMD.ExcessiveParameterList)

Definition at line 164 of file ProcessCronQueueObserver.php.

178  {
179  $this->_objectManager = $objectManager;
180  $this->_scheduleFactory = $scheduleFactory;
181  $this->_cache = $cache;
182  $this->_config = $config;
183  $this->_scopeConfig = $scopeConfig;
184  $this->_request = $request;
185  $this->_shell = $shell;
186  $this->dateTime = $dateTime;
187  $this->phpExecutableFinder = $phpExecutableFinderFactory->create();
188  $this->logger = $logger;
189  $this->state = $state;
190  $this->statProfiler = $statFactory->create();
191  $this->lockManager = $lockManager;
192  }
$objectManager
Definition: bootstrap.php:17
$config
Definition: fraud_order.php:17
if(!file_exists($installConfigFile)) if(!defined('TESTS_INSTALLATION_DB_CONFIG_FILE')) $shell
Definition: bootstrap.php:46

Member Function Documentation

◆ _generateJobs()

_generateJobs (   $jobs,
  $exists,
  $groupId 
)
protected

Generate jobs for config information

Parameters
array$jobs
array$exists
string$groupId
Returns
void

Definition at line 455 of file ProcessCronQueueObserver.php.

456  {
457  foreach ($jobs as $jobCode => $jobConfig) {
458  $cronExpression = $this->getCronExpression($jobConfig);
459  if (!$cronExpression) {
460  continue;
461  }
462 
463  $timeInterval = $this->getScheduleTimeInterval($groupId);
464  $this->saveSchedule($jobCode, $cronExpression, $timeInterval, $exists);
465  }
466  }
saveSchedule($jobCode, $cronExpression, $timeInterval, $exists)

◆ _runJob()

_runJob (   $scheduledTime,
  $currentTime,
  $jobConfig,
  $schedule,
  $groupId 
)
protected

Execute job by calling specific class::method

Parameters
int$scheduledTime
int$currentTime
string[]$jobConfig
Schedule$schedule
string$groupId
Returns
void
Exceptions

Definition at line 289 of file ProcessCronQueueObserver.php.

290  {
291  $jobCode = $schedule->getJobCode();
292  $scheduleLifetime = $this->getCronGroupConfigurationValue($groupId, self::XML_PATH_SCHEDULE_LIFETIME);
293  $scheduleLifetime = $scheduleLifetime * self::SECONDS_IN_MINUTE;
294  if ($scheduledTime < $currentTime - $scheduleLifetime) {
295  $schedule->setStatus(Schedule::STATUS_MISSED);
296  throw new \Exception(sprintf('Cron Job %s is missed at %s', $jobCode, $schedule->getScheduledAt()));
297  }
298 
299  if (!isset($jobConfig['instance'], $jobConfig['method'])) {
300  $schedule->setStatus(Schedule::STATUS_ERROR);
301  throw new \Exception('No callbacks found');
302  }
303  $model = $this->_objectManager->create($jobConfig['instance']);
304  $callback = [$model, $jobConfig['method']];
305  if (!is_callable($callback)) {
306  $schedule->setStatus(Schedule::STATUS_ERROR);
307  throw new \Exception(
308  sprintf('Invalid callback: %s::%s can\'t be called', $jobConfig['instance'], $jobConfig['method'])
309  );
310  }
311 
312  $schedule->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp()))->save();
313 
314  $this->startProfiling();
315  try {
316  $this->logger->info(sprintf('Cron Job %s is run', $jobCode));
317  call_user_func_array($callback, [$schedule]);
318  } catch (\Throwable $e) {
319  $schedule->setStatus(Schedule::STATUS_ERROR);
320  $this->logger->error(sprintf(
321  'Cron Job %s has an error: %s. Statistics: %s',
322  $jobCode,
323  $e->getMessage(),
324  $this->getProfilingStat()
325  ));
326  if (!$e instanceof \Exception) {
327  $e = new \RuntimeException(
328  'Error when running a cron job',
329  0,
330  $e
331  );
332  }
333  throw $e;
334  } finally {
335  $this->stopProfiling();
336  }
337 
338  $schedule->setStatus(Schedule::STATUS_SUCCESS)->setFinishedAt(strftime(
339  '%Y-%m-%d %H:%M:%S',
340  $this->dateTime->gmtTimestamp()
341  ));
342 
343  $this->logger->info(sprintf(
344  'Cron Job %s is successfully finished. Statistics: %s',
345  $jobCode,
346  $this->getProfilingStat()
347  ));
348  }

◆ createSchedule()

createSchedule (   $jobCode,
  $cronExpression,
  $time 
)
protected

Create a schedule of cron job.

Parameters
string$jobCode
string$cronExpression
int$time
Returns
Schedule

Definition at line 580 of file ProcessCronQueueObserver.php.

581  {
582  $schedule = $this->_scheduleFactory->create()
583  ->setCronExpr($cronExpression)
584  ->setJobCode($jobCode)
585  ->setStatus(Schedule::STATUS_PENDING)
586  ->setCreatedAt(strftime('%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp()))
587  ->setScheduledAt(strftime('%Y-%m-%d %H:%M', $time));
588 
589  return $schedule;
590  }

◆ execute()

execute ( \Magento\Framework\Event\Observer  $observer)

Process cron queue Generate tasks schedule Cleanup tasks schedule

Parameters
\Magento\Framework\Event\Observer$observer
Returns
void @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.NPathComplexity) @SuppressWarnings(PHPMD.UnusedFormalParameter)

Definition at line 205 of file ProcessCronQueueObserver.php.

206  {
207 
208  $currentTime = $this->dateTime->gmtTimestamp();
209  $jobGroupsRoot = $this->_config->getJobs();
210  // sort jobs groups to start from used in separated process
211  uksort(
212  $jobGroupsRoot,
213  function ($a, $b) {
214  return $this->getCronGroupConfigurationValue($b, 'use_separate_process')
215  - $this->getCronGroupConfigurationValue($a, 'use_separate_process');
216  }
217  );
218 
219  $phpPath = $this->phpExecutableFinder->find() ?: 'php';
220 
221  foreach ($jobGroupsRoot as $groupId => $jobsRoot) {
222  if (!$this->isGroupInFilter($groupId)) {
223  continue;
224  }
225  if ($this->_request->getParam(self::STANDALONE_PROCESS_STARTED) !== '1'
226  && $this->getCronGroupConfigurationValue($groupId, 'use_separate_process') == 1
227  ) {
228  $this->_shell->execute(
229  $phpPath . ' %s cron:run --group=' . $groupId . ' --' . Cli::INPUT_KEY_BOOTSTRAP . '='
230  . self::STANDALONE_PROCESS_STARTED . '=1',
231  [
232  BP . '/bin/magento'
233  ]
234  );
235  continue;
236  }
237 
238  $this->lockGroup(
239  $groupId,
240  function ($groupId) use ($currentTime, $jobsRoot) {
241  $this->cleanupJobs($groupId, $currentTime);
242  $this->generateSchedules($groupId);
243  $this->processPendingJobs($groupId, $jobsRoot, $currentTime);
244  }
245  );
246  }
247  }
const BP
Definition: autoload.php:14

◆ getConfigSchedule()

getConfigSchedule (   $jobConfig)
protected

Get config of schedule.

Parameters
array$jobConfig
Returns
mixed

Definition at line 528 of file ProcessCronQueueObserver.php.

529  {
530  $cronExpr = $this->_scopeConfig->getValue(
531  $jobConfig['config_path'],
532  \Magento\Store\Model\ScopeInterface::SCOPE_STORE
533  );
534 
535  return $cronExpr;
536  }

◆ getScheduleTimeInterval()

getScheduleTimeInterval (   $groupId)
protected

Get time interval for scheduling.

Parameters
string$groupId
Returns
int

Definition at line 598 of file ProcessCronQueueObserver.php.

599  {
600  $scheduleAheadFor = (int)$this->getCronGroupConfigurationValue($groupId, self::XML_PATH_SCHEDULE_AHEAD_FOR);
601  $scheduleAheadFor = $scheduleAheadFor * self::SECONDS_IN_MINUTE;
602 
603  return $scheduleAheadFor;
604  }

◆ saveSchedule()

saveSchedule (   $jobCode,
  $cronExpression,
  $timeInterval,
  $exists 
)
protected

Save a schedule of cron job.

Parameters
string$jobCode
string$cronExpression
int$timeInterval
array$exists
Returns
void

Definition at line 547 of file ProcessCronQueueObserver.php.

548  {
549  $currentTime = $this->dateTime->gmtTimestamp();
550  $timeAhead = $currentTime + $timeInterval;
551  for ($time = $currentTime; $time < $timeAhead; $time += self::SECONDS_IN_MINUTE) {
552  $scheduledAt = strftime('%Y-%m-%d %H:%M:00', $time);
553  $alreadyScheduled = !empty($exists[$jobCode . '/' . $scheduledAt]);
554  $schedule = $this->createSchedule($jobCode, $cronExpression, $time);
555  $valid = $schedule->trySchedule();
556  if (!$valid) {
557  if ($alreadyScheduled) {
558  if (!isset($this->invalid[$jobCode])) {
559  $this->invalid[$jobCode] = [];
560  }
561  $this->invalid[$jobCode][] = $scheduledAt;
562  }
563  continue;
564  }
565  if (!$alreadyScheduled) {
566  // time matches cron expression
567  $schedule->save();
568  }
569  }
570  }

Field Documentation

◆ $_cache

$_cache
protected

Definition at line 91 of file ProcessCronQueueObserver.php.

◆ $_config

$_config
protected

Definition at line 81 of file ProcessCronQueueObserver.php.

◆ $_objectManager

$_objectManager
protected

Definition at line 86 of file ProcessCronQueueObserver.php.

◆ $_pendingSchedules

$_pendingSchedules
protected

Definition at line 76 of file ProcessCronQueueObserver.php.

◆ $_request

$_request
protected

Definition at line 106 of file ProcessCronQueueObserver.php.

◆ $_scheduleFactory

$_scheduleFactory
protected

Definition at line 101 of file ProcessCronQueueObserver.php.

◆ $_scopeConfig

$_scopeConfig
protected

Definition at line 96 of file ProcessCronQueueObserver.php.

◆ $_shell

$_shell
protected

Definition at line 111 of file ProcessCronQueueObserver.php.

◆ $dateTime

$dateTime
protected

Definition at line 116 of file ProcessCronQueueObserver.php.

◆ $phpExecutableFinder

$phpExecutableFinder
protected

Definition at line 121 of file ProcessCronQueueObserver.php.

◆ CACHE_KEY_LAST_HISTORY_CLEANUP_AT

const CACHE_KEY_LAST_HISTORY_CLEANUP_AT = 'cron_last_history_cleanup_at'

Definition at line 31 of file ProcessCronQueueObserver.php.

◆ CACHE_KEY_LAST_SCHEDULE_GENERATE_AT

const CACHE_KEY_LAST_SCHEDULE_GENERATE_AT = 'cron_last_schedule_generate_at'

#+ Cache key values

Definition at line 29 of file ProcessCronQueueObserver.php.

◆ LOCK_PREFIX

const LOCK_PREFIX = 'CRON_GROUP_'

Static lock prefix for cron group locking

Definition at line 71 of file ProcessCronQueueObserver.php.

◆ LOCK_TIMEOUT

const LOCK_TIMEOUT = 5

How long to wait for cron group to become unlocked

Definition at line 66 of file ProcessCronQueueObserver.php.

◆ SECONDS_IN_MINUTE

const SECONDS_IN_MINUTE = 60

#- Value of seconds in one minute

Definition at line 61 of file ProcessCronQueueObserver.php.

◆ STANDALONE_PROCESS_STARTED

const STANDALONE_PROCESS_STARTED = 'standaloneProcessStarted'

Flag for internal communication between processes for running all jobs in a group in parallel as a separate process

Definition at line 37 of file ProcessCronQueueObserver.php.

◆ XML_PATH_HISTORY_CLEANUP_EVERY

const XML_PATH_HISTORY_CLEANUP_EVERY = 'history_cleanup_every'

Definition at line 50 of file ProcessCronQueueObserver.php.

◆ XML_PATH_HISTORY_FAILURE

const XML_PATH_HISTORY_FAILURE = 'history_failure_lifetime'

Definition at line 54 of file ProcessCronQueueObserver.php.

◆ XML_PATH_HISTORY_SUCCESS

const XML_PATH_HISTORY_SUCCESS = 'history_success_lifetime'

Definition at line 52 of file ProcessCronQueueObserver.php.

◆ XML_PATH_SCHEDULE_AHEAD_FOR

const XML_PATH_SCHEDULE_AHEAD_FOR = 'schedule_ahead_for'

Definition at line 46 of file ProcessCronQueueObserver.php.

◆ XML_PATH_SCHEDULE_GENERATE_EVERY

const XML_PATH_SCHEDULE_GENERATE_EVERY = 'schedule_generate_every'

#- #+ List of configurable constants used to calculate and validate during handling cron jobs

Definition at line 44 of file ProcessCronQueueObserver.php.

◆ XML_PATH_SCHEDULE_LIFETIME

const XML_PATH_SCHEDULE_LIFETIME = 'schedule_lifetime'

Definition at line 48 of file ProcessCronQueueObserver.php.


The documentation for this class was generated from the following file: