forked from magento/magento2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessCronQueueObserver.php
749 lines (669 loc) · 23.5 KB
/
ProcessCronQueueObserver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Handling cron jobs
*/
namespace Magento\Cron\Observer;
use Magento\Framework\App\State;
use Magento\Framework\Console\Cli;
use Magento\Framework\Event\ObserverInterface;
use \Magento\Cron\Model\Schedule;
use Magento\Framework\Profiler\Driver\Standard\Stat;
use Magento\Framework\Profiler\Driver\Standard\StatFactory;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ProcessCronQueueObserver implements ObserverInterface
{
/**#@+
* Cache key values
*/
const CACHE_KEY_LAST_SCHEDULE_GENERATE_AT = 'cron_last_schedule_generate_at';
const CACHE_KEY_LAST_HISTORY_CLEANUP_AT = 'cron_last_history_cleanup_at';
/**
* Flag for internal communication between processes for running
* all jobs in a group in parallel as a separate process
*/
const STANDALONE_PROCESS_STARTED = 'standaloneProcessStarted';
/**#@-*/
/**#@+
* List of configurable constants used to calculate and validate during handling cron jobs
*/
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';
/**#@-*/
/**
* Value of seconds in one minute
*/
const SECONDS_IN_MINUTE = 60;
/**
* How long to wait for cron group to become unlocked
*/
const LOCK_TIMEOUT = 5;
/**
* Static lock prefix for cron group locking
*/
const LOCK_PREFIX = 'CRON_GROUP_';
/**
* @var \Magento\Cron\Model\ResourceModel\Schedule\Collection
*/
protected $_pendingSchedules;
/**
* @var \Magento\Cron\Model\ConfigInterface
*/
protected $_config;
/**
* @var \Magento\Framework\App\ObjectManager
*/
protected $_objectManager;
/**
* @var \Magento\Framework\App\CacheInterface
*/
protected $_cache;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* @var ScheduleFactory
*/
protected $_scheduleFactory;
/**
* @var \Magento\Framework\App\Console\Request
*/
protected $_request;
/**
* @var \Magento\Framework\ShellInterface
*/
protected $_shell;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $dateTime;
/**
* @var \Symfony\Component\Process\PhpExecutableFinder
*/
protected $phpExecutableFinder;
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
/**
* @var \Magento\Framework\App\State
*/
private $state;
/**
* @var \Magento\Framework\Lock\LockManagerInterface
*/
private $lockManager;
/**
* @var array
*/
private $invalid = [];
/**
* @var Stat
*/
private $statProfiler;
/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param \Magento\Cron\Model\ScheduleFactory $scheduleFactory
* @param \Magento\Framework\App\CacheInterface $cache
* @param \Magento\Cron\Model\ConfigInterface $config
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\App\Console\Request $request
* @param \Magento\Framework\ShellInterface $shell
* @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
* @param \Magento\Framework\Process\PhpExecutableFinderFactory $phpExecutableFinderFactory
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Framework\App\State $state
* @param StatFactory $statFactory
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __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
) {
$this->_objectManager = $objectManager;
$this->_scheduleFactory = $scheduleFactory;
$this->_cache = $cache;
$this->_config = $config;
$this->_scopeConfig = $scopeConfig;
$this->_request = $request;
$this->_shell = $shell;
$this->dateTime = $dateTime;
$this->phpExecutableFinder = $phpExecutableFinderFactory->create();
$this->logger = $logger;
$this->state = $state;
$this->statProfiler = $statFactory->create();
$this->lockManager = $lockManager;
}
/**
* Process cron queue
* Generate tasks schedule
* Cleanup tasks schedule
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$currentTime = $this->dateTime->gmtTimestamp();
$jobGroupsRoot = $this->_config->getJobs();
// sort jobs groups to start from used in separated process
uksort(
$jobGroupsRoot,
function ($a, $b) {
return $this->getCronGroupConfigurationValue($b, 'use_separate_process')
- $this->getCronGroupConfigurationValue($a, 'use_separate_process');
}
);
$phpPath = $this->phpExecutableFinder->find() ?: 'php';
foreach ($jobGroupsRoot as $groupId => $jobsRoot) {
if (!$this->isGroupInFilter($groupId)) {
continue;
}
if ($this->_request->getParam(self::STANDALONE_PROCESS_STARTED) !== '1'
&& $this->getCronGroupConfigurationValue($groupId, 'use_separate_process') == 1
) {
$this->_shell->execute(
$phpPath . ' %s cron:run --group=' . $groupId . ' --' . Cli::INPUT_KEY_BOOTSTRAP . '='
. self::STANDALONE_PROCESS_STARTED . '=1',
[
BP . '/bin/magento'
]
);
continue;
}
$this->lockGroup(
$groupId,
function ($groupId) use ($currentTime, $jobsRoot) {
$this->cleanupJobs($groupId, $currentTime);
$this->generateSchedules($groupId);
$this->processPendingJobs($groupId, $jobsRoot, $currentTime);
}
);
}
}
/**
* Lock group
*
* It should be taken by standalone (child) process, not by the parent process.
*
* @param int $groupId
* @param callable $callback
*
* @return void
*/
private function lockGroup($groupId, callable $callback)
{
if (!$this->lockManager->lock(self::LOCK_PREFIX . $groupId, self::LOCK_TIMEOUT)) {
$this->logger->warning(
sprintf(
"Could not acquire lock for cron group: %s, skipping run",
$groupId
)
);
return;
}
try {
$callback($groupId);
} finally {
$this->lockManager->unlock(self::LOCK_PREFIX . $groupId);
}
}
/**
* Execute job by calling specific class::method
*
* @param int $scheduledTime
* @param int $currentTime
* @param string[] $jobConfig
* @param Schedule $schedule
* @param string $groupId
* @return void
* @throws \Exception
*/
protected function _runJob($scheduledTime, $currentTime, $jobConfig, $schedule, $groupId)
{
$jobCode = $schedule->getJobCode();
$scheduleLifetime = $this->getCronGroupConfigurationValue($groupId, self::XML_PATH_SCHEDULE_LIFETIME);
$scheduleLifetime = $scheduleLifetime * self::SECONDS_IN_MINUTE;
if ($scheduledTime < $currentTime - $scheduleLifetime) {
$schedule->setStatus(Schedule::STATUS_MISSED);
throw new \Exception(sprintf('Cron Job %s is missed at %s', $jobCode, $schedule->getScheduledAt()));
}
if (!isset($jobConfig['instance'], $jobConfig['method'])) {
$schedule->setStatus(Schedule::STATUS_ERROR);
throw new \Exception('No callbacks found');
}
$model = $this->_objectManager->create($jobConfig['instance']);
$callback = [$model, $jobConfig['method']];
if (!is_callable($callback)) {
$schedule->setStatus(Schedule::STATUS_ERROR);
throw new \Exception(
sprintf('Invalid callback: %s::%s can\'t be called', $jobConfig['instance'], $jobConfig['method'])
);
}
$schedule->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp()))->save();
$this->startProfiling();
try {
$this->logger->info(sprintf('Cron Job %s is run', $jobCode));
call_user_func_array($callback, [$schedule]);
} catch (\Throwable $e) {
$schedule->setStatus(Schedule::STATUS_ERROR);
$this->logger->error(sprintf(
'Cron Job %s has an error: %s. Statistics: %s',
$jobCode,
$e->getMessage(),
$this->getProfilingStat()
));
if (!$e instanceof \Exception) {
$e = new \RuntimeException(
'Error when running a cron job',
0,
$e
);
}
throw $e;
} finally {
$this->stopProfiling();
}
$schedule->setStatus(Schedule::STATUS_SUCCESS)->setFinishedAt(strftime(
'%Y-%m-%d %H:%M:%S',
$this->dateTime->gmtTimestamp()
));
$this->logger->info(sprintf(
'Cron Job %s is successfully finished. Statistics: %s',
$jobCode,
$this->getProfilingStat()
));
}
/**
* Starts profiling
*
* @return void
*/
private function startProfiling()
{
$this->statProfiler->clear();
$this->statProfiler->start('job', microtime(true), memory_get_usage(true), memory_get_usage());
}
/**
* Stops profiling
*
* @return void
*/
private function stopProfiling()
{
$this->statProfiler->stop('job', microtime(true), memory_get_usage(true), memory_get_usage());
}
/**
* Retrieves statistics in the JSON format
*
* @return string
*/
private function getProfilingStat()
{
$stat = $this->statProfiler->get('job');
unset($stat[Stat::START]);
return json_encode($stat);
}
/**
* Return job collection from data base with status 'pending'
*
* @return \Magento\Cron\Model\ResourceModel\Schedule\Collection
*/
private function getPendingSchedules($groupId)
{
$jobs = $this->_config->getJobs();
$pendingJobs = $this->_scheduleFactory->create()->getCollection();
$pendingJobs->addFieldToFilter('status', Schedule::STATUS_PENDING);
$pendingJobs->addFieldToFilter('job_code', ['in' => array_keys($jobs[$groupId])]);
return $pendingJobs;
}
/**
* Generate cron schedule
*
* @param string $groupId
* @return $this
*/
private function generateSchedules($groupId)
{
/**
* check if schedule generation is needed
*/
$lastRun = (int)$this->_cache->load(self::CACHE_KEY_LAST_SCHEDULE_GENERATE_AT . $groupId);
$rawSchedulePeriod = (int)$this->getCronGroupConfigurationValue(
$groupId,
self::XML_PATH_SCHEDULE_GENERATE_EVERY
);
$schedulePeriod = $rawSchedulePeriod * self::SECONDS_IN_MINUTE;
if ($lastRun > $this->dateTime->gmtTimestamp() - $schedulePeriod) {
return $this;
}
/**
* save time schedules generation was ran with no expiration
*/
$this->_cache->save(
$this->dateTime->gmtTimestamp(),
self::CACHE_KEY_LAST_SCHEDULE_GENERATE_AT . $groupId,
['crontab'],
null
);
$schedules = $this->getPendingSchedules($groupId);
$exists = [];
/** @var Schedule $schedule */
foreach ($schedules as $schedule) {
$exists[$schedule->getJobCode() . '/' . $schedule->getScheduledAt()] = 1;
}
/**
* generate global crontab jobs
*/
$jobs = $this->_config->getJobs();
$this->invalid = [];
$this->_generateJobs($jobs[$groupId], $exists, $groupId);
$this->cleanupScheduleMismatches();
return $this;
}
/**
* Generate jobs for config information
*
* @param array $jobs
* @param array $exists
* @param string $groupId
* @return void
*/
protected function _generateJobs($jobs, $exists, $groupId)
{
foreach ($jobs as $jobCode => $jobConfig) {
$cronExpression = $this->getCronExpression($jobConfig);
if (!$cronExpression) {
continue;
}
$timeInterval = $this->getScheduleTimeInterval($groupId);
$this->saveSchedule($jobCode, $cronExpression, $timeInterval, $exists);
}
}
/**
* Clean expired jobs
*
* @param $groupId
* @param $currentTime
* @return void
*/
private function cleanupJobs($groupId, $currentTime)
{
// check if history cleanup is needed
$lastCleanup = (int)$this->_cache->load(self::CACHE_KEY_LAST_HISTORY_CLEANUP_AT . $groupId);
$historyCleanUp = (int)$this->getCronGroupConfigurationValue($groupId, self::XML_PATH_HISTORY_CLEANUP_EVERY);
if ($lastCleanup > $this->dateTime->gmtTimestamp() - $historyCleanUp * self::SECONDS_IN_MINUTE) {
return $this;
}
// save time history cleanup was ran with no expiration
$this->_cache->save(
$this->dateTime->gmtTimestamp(),
self::CACHE_KEY_LAST_HISTORY_CLEANUP_AT . $groupId,
['crontab'],
null
);
$this->cleanupDisabledJobs($groupId);
$historySuccess = (int)$this->getCronGroupConfigurationValue($groupId, self::XML_PATH_HISTORY_SUCCESS);
$historyFailure = (int)$this->getCronGroupConfigurationValue($groupId, self::XML_PATH_HISTORY_FAILURE);
$historyLifetimes = [
Schedule::STATUS_SUCCESS => $historySuccess * self::SECONDS_IN_MINUTE,
Schedule::STATUS_MISSED => $historyFailure * self::SECONDS_IN_MINUTE,
Schedule::STATUS_ERROR => $historyFailure * self::SECONDS_IN_MINUTE,
Schedule::STATUS_PENDING => max($historyFailure, $historySuccess) * self::SECONDS_IN_MINUTE,
];
$jobs = $this->_config->getJobs()[$groupId];
$scheduleResource = $this->_scheduleFactory->create()->getResource();
$connection = $scheduleResource->getConnection();
$count = 0;
foreach ($historyLifetimes as $time) {
$count += $connection->delete(
$scheduleResource->getMainTable(),
[
'status = ?' => Schedule::STATUS_PENDING,
'job_code in (?)' => array_keys($jobs),
'created_at < ?' => $connection->formatDate($currentTime - $time)
]
);
}
if ($count) {
$this->logger->info(sprintf('%d cron jobs were cleaned', $count));
}
}
/**
* @param array $jobConfig
* @return mixed
*/
protected function getConfigSchedule($jobConfig)
{
$cronExpr = $this->_scopeConfig->getValue(
$jobConfig['config_path'],
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
return $cronExpr;
}
/**
* @param string $jobCode
* @param string $cronExpression
* @param int $timeInterval
* @param array $exists
* @return void
*/
protected function saveSchedule($jobCode, $cronExpression, $timeInterval, $exists)
{
$currentTime = $this->dateTime->gmtTimestamp();
$timeAhead = $currentTime + $timeInterval;
for ($time = $currentTime; $time < $timeAhead; $time += self::SECONDS_IN_MINUTE) {
$scheduledAt = strftime('%Y-%m-%d %H:%M:00', $time);
$alreadyScheduled = !empty($exists[$jobCode . '/' . $scheduledAt]);
$schedule = $this->createSchedule($jobCode, $cronExpression, $time);
$valid = $schedule->trySchedule();
if (!$valid) {
if ($alreadyScheduled) {
if (!isset($this->invalid[$jobCode])) {
$this->invalid[$jobCode] = [];
}
$this->invalid[$jobCode][] = $scheduledAt;
}
continue;
}
if (!$alreadyScheduled) {
// time matches cron expression
$schedule->save();
}
}
}
/**
* @param string $jobCode
* @param string $cronExpression
* @param int $time
* @return Schedule
*/
protected function createSchedule($jobCode, $cronExpression, $time)
{
$schedule = $this->_scheduleFactory->create()
->setCronExpr($cronExpression)
->setJobCode($jobCode)
->setStatus(Schedule::STATUS_PENDING)
->setCreatedAt(strftime('%Y-%m-%d %H:%M:%S', $this->dateTime->gmtTimestamp()))
->setScheduledAt(strftime('%Y-%m-%d %H:%M', $time));
return $schedule;
}
/**
* @param string $groupId
* @return int
*/
protected function getScheduleTimeInterval($groupId)
{
$scheduleAheadFor = (int)$this->getCronGroupConfigurationValue($groupId, self::XML_PATH_SCHEDULE_AHEAD_FOR);
$scheduleAheadFor = $scheduleAheadFor * self::SECONDS_IN_MINUTE;
return $scheduleAheadFor;
}
/**
* Clean up scheduled jobs that are disabled in the configuration
* This can happen when you turn off a cron job in the config and flush the cache
*
* @param string $groupId
* @return void
*/
private function cleanupDisabledJobs($groupId)
{
$jobs = $this->_config->getJobs();
$jobsToCleanup = [];
foreach ($jobs[$groupId] as $jobCode => $jobConfig) {
if (!$this->getCronExpression($jobConfig)) {
/** @var \Magento\Cron\Model\ResourceModel\Schedule $scheduleResource */
$jobsToCleanup[] = $jobCode;
}
}
if (count($jobsToCleanup) > 0) {
$scheduleResource = $this->_scheduleFactory->create()->getResource();
$count = $scheduleResource->getConnection()->delete(
$scheduleResource->getMainTable(),
[
'status = ?' => Schedule::STATUS_PENDING,
'job_code in (?)' => $jobsToCleanup,
]
);
$this->logger->info(sprintf('%d cron jobs were cleaned', $count));
}
}
/**
* @param array $jobConfig
* @return null|string
*/
private function getCronExpression($jobConfig)
{
$cronExpression = null;
if (isset($jobConfig['config_path'])) {
$cronExpression = $this->getConfigSchedule($jobConfig) ?: null;
}
if (!$cronExpression) {
if (isset($jobConfig['schedule'])) {
$cronExpression = $jobConfig['schedule'];
}
}
return $cronExpression;
}
/**
* Clean up scheduled jobs that do not match their cron expression anymore
* This can happen when you change the cron expression and flush the cache
*
* @return $this
*/
private function cleanupScheduleMismatches()
{
/** @var \Magento\Cron\Model\ResourceModel\Schedule $scheduleResource */
$scheduleResource = $this->_scheduleFactory->create()->getResource();
foreach ($this->invalid as $jobCode => $scheduledAtList) {
$scheduleResource->getConnection()->delete($scheduleResource->getMainTable(), [
'status = ?' => Schedule::STATUS_PENDING,
'job_code = ?' => $jobCode,
'scheduled_at in (?)' => $scheduledAtList,
]);
}
return $this;
}
/**
* Get CronGroup Configuration Value
*
* @param $groupId
* @return int
*/
private function getCronGroupConfigurationValue($groupId, $path)
{
return $this->_scopeConfig->getValue(
'system/cron/' . $groupId . '/' . $path,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
/**
* Is Group In Filter
*
* @param $groupId
* @return bool
*/
private function isGroupInFilter($groupId): bool
{
return !($this->_request->getParam('group') !== null
&& trim($this->_request->getParam('group'), "'") !== $groupId);
}
/**
* Process pending jobs
*
* @param $groupId
* @param $jobsRoot
* @param $currentTime
*/
private function processPendingJobs($groupId, $jobsRoot, $currentTime)
{
$procesedJobs = [];
$pendingJobs = $this->getPendingSchedules($groupId);
/** @var \Magento\Cron\Model\Schedule $schedule */
foreach ($pendingJobs as $schedule) {
if (isset($procesedJobs[$schedule->getJobCode()])) {
// process only on job per run
continue;
}
$jobConfig = isset($jobsRoot[$schedule->getJobCode()]) ? $jobsRoot[$schedule->getJobCode()] : null;
if (!$jobConfig) {
continue;
}
$scheduledTime = strtotime($schedule->getScheduledAt());
if ($scheduledTime > $currentTime) {
continue;
}
try {
if ($schedule->tryLockJob()) {
$this->_runJob($scheduledTime, $currentTime, $jobConfig, $schedule, $groupId);
}
} catch (\Exception $e) {
$this->processError($schedule, $e);
}
if ($schedule->getStatus() === Schedule::STATUS_SUCCESS) {
$procesedJobs[$schedule->getJobCode()] = true;
}
$schedule->save();
}
}
/**
* @param Schedule $schedule
* @param \Exception $exception
* @return void
*/
private function processError(\Magento\Cron\Model\Schedule $schedule, \Exception $exception)
{
$schedule->setMessages($exception->getMessage());
if ($schedule->getStatus() === Schedule::STATUS_ERROR) {
$this->logger->critical($exception);
}
if ($schedule->getStatus() === Schedule::STATUS_MISSED
&& $this->state->getMode() === State::MODE_DEVELOPER
) {
$this->logger->info($schedule->getMessages());
}
}
}