1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Jellyfish\Scheduler; |
6
|
|
|
|
7
|
|
|
use Cron\CronExpression; |
8
|
|
|
use DateTime; |
9
|
|
|
use Jellyfish\Process\ProcessInterface; |
10
|
|
|
|
11
|
|
|
class Job implements JobInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var \Jellyfish\Process\ProcessInterface |
15
|
|
|
*/ |
16
|
|
|
protected $process; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var \Cron\CronExpression |
20
|
|
|
*/ |
21
|
|
|
protected $cronExpression; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param \Jellyfish\Process\ProcessInterface $process |
25
|
|
|
* @param \Cron\CronExpression $cronExpression |
26
|
|
|
*/ |
27
|
|
|
public function __construct( |
28
|
|
|
ProcessInterface $process, |
29
|
|
|
CronExpression $cronExpression |
30
|
|
|
) { |
31
|
|
|
$this->process = $process; |
32
|
|
|
$this->cronExpression = $cronExpression; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @return array |
37
|
|
|
*/ |
38
|
|
|
public function getCommand(): array |
39
|
|
|
{ |
40
|
|
|
return $this->process->getCommand(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @return \Cron\CronExpression |
45
|
|
|
*/ |
46
|
|
|
public function getCronExpression(): CronExpression |
47
|
|
|
{ |
48
|
|
|
return $this->cronExpression; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param \DateTime $dateTime |
53
|
|
|
* |
54
|
|
|
* @return bool |
55
|
|
|
*/ |
56
|
|
|
protected function isDue(DateTime $dateTime): bool |
57
|
|
|
{ |
58
|
|
|
return $this->cronExpression->isDue($dateTime); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param \DateTime|null $dateTime |
63
|
|
|
* |
64
|
|
|
* @return \Jellyfish\Scheduler\JobInterface |
65
|
|
|
* |
66
|
|
|
* @throws \Exception |
67
|
|
|
*/ |
68
|
|
|
public function run(?DateTime $dateTime = null): JobInterface |
69
|
|
|
{ |
70
|
|
|
if ($dateTime === null) { |
71
|
|
|
$dateTime = new DateTime(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
if (!$this->isDue($dateTime)) { |
75
|
|
|
return $this; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$this->process->start(); |
79
|
|
|
|
80
|
|
|
return $this; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @return bool |
85
|
|
|
*/ |
86
|
|
|
public function isRunning(): bool |
87
|
|
|
{ |
88
|
|
|
return $this->process->isRunning(); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|