-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathJobRunner.php
119 lines (97 loc) · 3 KB
/
JobRunner.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
<?php
namespace Enqueue\JobQueue;
class JobRunner
{
/**
* @var JobProcessor
*/
private $jobProcessor;
/**
* @var Job
*/
private $rootJob;
/**
* @param Job $rootJob
*/
public function __construct(JobProcessor $jobProcessor, Job $rootJob = null)
{
$this->jobProcessor = $jobProcessor;
$this->rootJob = $rootJob;
}
/**
* @param string $ownerId
* @param string $name
*
* @throws \Throwable|\Exception if $runCallback triggers an exception
*
* @return mixed
*/
public function runUnique($ownerId, $name, callable $runCallback)
{
$rootJob = $this->jobProcessor->findOrCreateRootJob($ownerId, $name, true);
if (!$rootJob) {
return;
}
$childJob = $this->jobProcessor->findOrCreateChildJob($name, $rootJob);
if (!$childJob->getStartedAt()) {
$this->jobProcessor->startChildJob($childJob);
}
$jobRunner = new self($this->jobProcessor, $rootJob);
try {
$result = call_user_func($runCallback, $jobRunner, $childJob);
} catch (\Throwable $e) {
try {
$this->jobProcessor->failChildJob($childJob);
} catch (\Throwable $t) {
throw new OrphanJobException(sprintf('Job cleanup failed. ID: "%s" Name: "%s"', $childJob->getId(), $childJob->getName()), 0, $e);
}
throw $e;
}
if (!$childJob->getStoppedAt()) {
$result
? $this->jobProcessor->successChildJob($childJob)
: $this->jobProcessor->failChildJob($childJob);
}
return $result;
}
/**
* @param string $name
*
* @return mixed
*/
public function createDelayed($name, callable $startCallback)
{
$childJob = $this->jobProcessor->findOrCreateChildJob($name, $this->rootJob);
$jobRunner = new self($this->jobProcessor, $this->rootJob);
return call_user_func($startCallback, $jobRunner, $childJob);
}
/**
* @param string $jobId
*
* @return mixed
*/
public function runDelayed($jobId, callable $runCallback)
{
$job = $this->jobProcessor->findJobById($jobId);
if (!$job) {
throw new \LogicException(sprintf('Job was not found. id: "%s"', $jobId));
}
if ($job->getRootJob()->isInterrupted()) {
if (!$job->getStoppedAt()) {
$this->jobProcessor->cancelChildJob($job);
}
return;
}
if (!$job->getStartedAt()) {
$this->jobProcessor->startChildJob($job);
}
$jobRunner = new self($this->jobProcessor, $job->getRootJob());
$result = call_user_func($runCallback, $jobRunner, $job);
if (!$job->getStoppedAt()) {
$result
? $this->jobProcessor->successChildJob($job)
: $this->jobProcessor->failChildJob($job);
}
return $result;
}
}