|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Copyright 2017 NanoSector |
|
5
|
|
|
* |
|
6
|
|
|
* You should have received a copy of the MIT license with the project. |
|
7
|
|
|
* See the LICENSE file for more information. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace Yoshi2889\Tasks; |
|
11
|
|
|
|
|
12
|
|
|
use React\EventLoop\LoopInterface; |
|
13
|
|
|
|
|
14
|
|
|
class TaskController |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var int |
|
18
|
|
|
*/ |
|
19
|
|
|
protected $loopInterval = 1; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var TaskInterface[] |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $tasks = []; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* TaskController constructor. |
|
28
|
|
|
* |
|
29
|
|
|
* @param LoopInterface $loop |
|
30
|
|
|
*/ |
|
31
|
9 |
|
public function __construct(LoopInterface $loop) |
|
32
|
|
|
{ |
|
33
|
9 |
|
$loop->addPeriodicTimer($this->loopInterval, [$this, 'runTasks']); |
|
34
|
9 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @param TaskInterface $task |
|
38
|
|
|
* |
|
39
|
|
|
* @return bool |
|
40
|
|
|
*/ |
|
41
|
9 |
|
public function add(TaskInterface $task): bool |
|
42
|
|
|
{ |
|
43
|
9 |
|
if ($this->exists($task)) |
|
44
|
1 |
|
return false; |
|
45
|
|
|
|
|
46
|
9 |
|
$this->tasks[] = $task; |
|
47
|
|
|
|
|
48
|
9 |
|
return true; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param TaskInterface $task |
|
53
|
|
|
* |
|
54
|
|
|
* @return bool |
|
55
|
|
|
*/ |
|
56
|
8 |
|
public function remove(TaskInterface $task): bool |
|
57
|
|
|
{ |
|
58
|
8 |
|
if (!$this->exists($task)) |
|
59
|
1 |
|
return false; |
|
60
|
|
|
|
|
61
|
8 |
|
unset($this->tasks[array_search($task, $this->tasks)]); |
|
62
|
|
|
|
|
63
|
8 |
|
return true; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
public function removeAll() |
|
67
|
|
|
{ |
|
68
|
1 |
|
foreach ($this->tasks as $task) |
|
69
|
|
|
{ |
|
70
|
1 |
|
$task->cancel(); |
|
71
|
1 |
|
$this->remove($task); |
|
72
|
|
|
} |
|
73
|
1 |
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @param TaskInterface $task |
|
77
|
|
|
* |
|
78
|
|
|
* @return bool |
|
79
|
|
|
*/ |
|
80
|
9 |
|
public function exists(TaskInterface $task): bool |
|
81
|
|
|
{ |
|
82
|
9 |
|
return in_array($task, $this->tasks); |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
6 |
|
public function runTasks() |
|
86
|
|
|
{ |
|
87
|
6 |
|
foreach ($this->tasks as $task) |
|
88
|
|
|
{ |
|
89
|
6 |
|
if (time() < $task->getExpiryTime()) |
|
90
|
1 |
|
continue; |
|
91
|
|
|
|
|
92
|
6 |
|
$result = $task->run(); |
|
93
|
|
|
|
|
94
|
|
|
// It is removed first. |
|
95
|
6 |
|
$this->remove($task); |
|
96
|
|
|
|
|
97
|
6 |
|
if ($result instanceof TaskInterface) |
|
98
|
2 |
|
$this->add($result); |
|
99
|
|
|
} |
|
100
|
|
|
} |
|
101
|
|
|
} |