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
|
<?php
namespace ipl\Scheduler;
use DateTime;
use InvalidArgumentException;
use ipl\Scheduler\Common\Promises;
use ipl\Scheduler\Common\Timers;
use ipl\Scheduler\Contract\Frequency;
use ipl\Scheduler\Contract\Task;
use ipl\Stdlib\Events;
use React\EventLoop\Loop;
use React\Promise;
use React\Promise\ExtendedPromiseInterface;
use SplObjectStorage;
use Throwable;
class Scheduler
{
use Events;
use Timers;
use Promises;
/**
* Event raised when a {@link Task task} is canceled
*
* The task and its pending operations as an array of canceled {@link ExtendedPromiseInterface promise}s
* are passed as parameters to the event callbacks.
*
* **Example usage:**
*
* ```php
* $scheduler->on($scheduler::ON_TASK_CANCEL, function (Task $task, array $_) use ($logger) {
* $logger->info(sprintf('Task %s cancelled', $task->getName()));
* });
* ```
*/
public const ON_TASK_CANCEL = 'task-cancel';
/**
* Event raised when an operation of a {@link Task task} is done
*
* The task and the operation result are passed as parameters to the event callbacks.
*
* **Example usage:**
*
* ```php
* $scheduler->on($scheduler::ON_TASK_DONE, function (Task $task, $result) use ($logger) {
* $logger->info(sprintf('Operation of task %s done: %s', $task->getName(), $result));
* });
* ```
*/
public const ON_TASK_DONE = 'task-done';
/**
* Event raised when an operation of a {@link Task task} failed
*
* The task and the {@link Throwable reason} why the operation failed
* are passed as parameters to the event callbacks.
*
* **Example usage:**
*
* ```php
* $scheduler->on($scheduler::ON_TASK_FAILED, function (Task $task, Throwable $e) use ($logger) {
* $logger->error(
* sprintf('Operation of task %s failed: %s', $task->getName(), $e),
* ['exception' => $e]
* );
* });
* ```
*/
public const ON_TASK_FAILED = 'task-failed';
/**
* Event raised when a {@link Task task} operation is scheduled
*
* The task and the {@link DateTime time} when it should run
* are passed as parameters to the event callbacks.
*
* **Example usage:**
*
* ```php
* $scheduler->on($scheduler::ON_TASK_SCHEDULED, function (Task $task, DateTime $dateTime) use ($logger) {
* $logger->info(sprintf(
* 'Scheduling task %s to run at %s',
* $task->getName(),
* IntlDateFormatter::formatObject($dateTime)
* ));
* });
* ```
*/
public const ON_TASK_SCHEDULED = 'task-scheduled';
/**
* Event raised upon operation of a {@link Task task}
*
* The task and the possibly not yet completed result of the operation as a {@link ExtendedPromiseInterface promise}
* are passed as parameters to the event callbacks.
*
* **Example usage:**
*
* ```php
* $scheduler->on($scheduler::ON_TASK_OPERATION, function (Task $task, ExtendedPromiseInterface $_) use ($logger) {
* $logger->info(sprintf('Task %s operating', $task->getName()));
* });
* ```
*/
public const ON_TASK_RUN = 'task-run';
/**
* Event raised when a {@see Task task} is expired
*
* The task and the {@see DateTime expire time} are passed as parameters to the event callbacks.
* Note that the expiration time is the first time that is considered expired based on the frequency
* of the task and can be later than the specified end time.
*
* **Example usage:**
*
* ```php
* $scheduler->on(Scheduler::ON_TASK_EXPIRED, function (Task $task, DateTime $dateTime) use ($logger) {
* $logger->info(sprintf('Removing expired task %s at %s', $task->getName(), $dateTime->format('Y-m-d H:i:s')));
* });
* ```
*/
public const ON_TASK_EXPIRED = 'task-expired';
/** @var SplObjectStorage<Task, null> The scheduled tasks of this scheduler */
protected $tasks;
public function __construct()
{
$this->tasks = new SplObjectStorage();
$this->promises = new SplObjectStorage();
$this->timers = new SplObjectStorage();
$this->init();
}
/**
* Initialize this scheduler
*/
protected function init(): void
{
}
/**
* Remove and cancel the given task
*
* @param Task $task
*
* @return $this
*
* @throws InvalidArgumentException If the given task isn't scheduled
*/
public function remove(Task $task): self
{
if (! $this->hasTask($task)) {
throw new InvalidArgumentException(sprintf('Task %s not scheduled', $task->getName()));
}
$this->cancelTask($task);
$this->tasks->detach($task);
return $this;
}
/**
* Remove and cancel all tasks
*
* @return $this
*/
public function removeTasks(): self
{
foreach ($this->tasks as $task) {
$this->cancelTask($task);
}
$this->tasks = new SplObjectStorage();
return $this;
}
/**
* Get whether the specified task is scheduled
*
* @param Task $task
*
* @return bool
*/
public function hasTask(Task $task): bool
{
return $this->tasks->contains($task);
}
/**
* Schedule the given task based on the specified frequency
*
* @param Task $task
* @param Frequency $frequency
*
* @return $this
*/
public function schedule(Task $task, Frequency $frequency): self
{
$now = new DateTime();
if ($frequency->isExpired($now)) {
return $this;
}
if ($frequency->isDue($now)) {
Loop::futureTick(function () use ($task): void {
$promise = $this->runTask($task);
$this->emit(static::ON_TASK_RUN, [$task, $promise]);
});
$this->emit(static::ON_TASK_SCHEDULED, [$task, $now]);
if ($frequency instanceof OneOff) {
return $this;
}
}
$loop = function () use (&$loop, $task, $frequency): void {
$promise = $this->runTask($task);
$this->emit(static::ON_TASK_RUN, [$task, $promise]);
$now = new DateTime();
$nextDue = $frequency->getNextDue($now);
if ($frequency instanceof OneOff || $frequency->isExpired($nextDue)) {
$removeTask = function () use ($task, $nextDue): void {
$this->remove($task);
$this->emit(static::ON_TASK_EXPIRED, [$task, $nextDue]);
};
if ($this->promises->contains($task->getUuid())) {
$pendingPromises = (array) $this->promises->offsetGet($task->getUuid());
Promise\all($pendingPromises)->always($removeTask);
} else {
$removeTask();
}
return;
}
$this->attachTimer(
$task->getUuid(),
Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $loop)
);
$this->emit(static::ON_TASK_SCHEDULED, [$task, $nextDue]);
};
$nextDue = $frequency->getNextDue($now);
$this->attachTimer(
$task->getUuid(),
Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $loop)
);
$this->emit(static::ON_TASK_SCHEDULED, [$task, $nextDue]);
$this->tasks->attach($task);
return $this;
}
public function isValidEvent(string $event): bool
{
$events = array_flip([
static::ON_TASK_CANCEL,
static::ON_TASK_DONE,
static::ON_TASK_EXPIRED,
static::ON_TASK_FAILED,
static::ON_TASK_RUN,
static::ON_TASK_SCHEDULED
]);
return isset($events[$event]);
}
/**
* Cancel the timer of the task and all pending operations
*
* @param Task $task
*/
protected function cancelTask(Task $task): void
{
Loop::cancelTimer($this->detachTimer($task->getUuid()));
/** @var ExtendedPromiseInterface[] $promises */
$promises = $this->detachPromises($task->getUuid());
if (! empty($promises)) {
/** @var Promise\CancellablePromiseInterface $promise */
foreach ($promises as $promise) {
$promise->cancel();
}
$this->emit(self::ON_TASK_CANCEL, [$task, $promises]);
}
}
/**
* Runs the given task immediately and registers handlers for the returned promise
*
* @param Task $task
*
* @return ExtendedPromiseInterface
*/
protected function runTask(Task $task): ExtendedPromiseInterface
{
$promise = $task->run();
$this->addPromise($task->getUuid(), $promise);
return $promise->then(
function ($result) use ($task): void {
$this->emit(self::ON_TASK_DONE, [$task, $result]);
},
function (Throwable $reason) use ($task): void {
$this->emit(self::ON_TASK_FAILED, [$task, $reason]);
}
)->always(function () use ($task, $promise): void {
// Unregister the promise without canceling it as it's already resolved
$this->removePromise($task->getUuid(), $promise);
});
}
}
|