| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Scheduler; |
| 4 |
|
| 5 |
use DateTime; |
| 6 |
use InvalidArgumentException; |
| 7 |
use ipl\Scheduler\Common\Promises; |
| 8 |
use ipl\Scheduler\Common\Timers; |
| 9 |
use ipl\Scheduler\Contract\Frequency; |
| 10 |
use ipl\Scheduler\Contract\Task; |
| 11 |
use ipl\Stdlib\Events; |
| 12 |
use React\EventLoop\Loop; |
| 13 |
use React\Promise; |
| 14 |
use React\Promise\PromiseInterface; |
| 15 |
use SplObjectStorage; |
| 16 |
use Throwable; |
| 17 |
|
| 18 |
/** |
| 19 |
* Task scheduler driven by the ReactPHP event loop |
| 20 |
* |
| 21 |
* Schedules {@see Task} instances according to their {@see Frequency} and emits lifecycle events |
| 22 |
* that consumers can listen to via {@see Scheduler::on()}. See the public `ON_*` constants for available events. |
| 23 |
*/ |
| 24 |
class Scheduler |
| 25 |
{ |
| 26 |
use Events; |
| 27 |
use Timers; |
| 28 |
use Promises; |
| 29 |
|
| 30 |
/** |
| 31 |
* Event raised when a {@see Task task} is canceled |
| 32 |
* |
| 33 |
* The task and its pending operations as an array of canceled {@see PromiseInterface promise}s |
| 34 |
* are passed as parameters to the event callbacks. |
| 35 |
* |
| 36 |
* **Example usage:** |
| 37 |
* |
| 38 |
* $scheduler->on($scheduler::ON_TASK_CANCEL, function (Task $task, array $_) use ($logger) { |
| 39 |
* $logger->info(sprintf('Task %s cancelled', $task->getName())); |
| 40 |
* }); |
| 41 |
*/ |
| 42 |
public const ON_TASK_CANCEL = 'task-cancel'; |
| 43 |
|
| 44 |
/** |
| 45 |
* Event raised when an operation of a {@see Task task} is done |
| 46 |
* |
| 47 |
* The task and the operation result are passed as parameters to the event callbacks. |
| 48 |
* |
| 49 |
* **Example usage:** |
| 50 |
* |
| 51 |
* $scheduler->on($scheduler::ON_TASK_DONE, function (Task $task, $result) use ($logger) { |
| 52 |
* $logger->info(sprintf('Operation of task %s done: %s', $task->getName(), $result)); |
| 53 |
* }); |
| 54 |
*/ |
| 55 |
public const ON_TASK_DONE = 'task-done'; |
| 56 |
|
| 57 |
/** |
| 58 |
* Event raised when an operation of a {@see Task task} failed |
| 59 |
* |
| 60 |
* The task and the {@see Throwable reason} why the operation failed |
| 61 |
* are passed as parameters to the event callbacks. |
| 62 |
* |
| 63 |
* **Example usage:** |
| 64 |
* |
| 65 |
* $scheduler->on($scheduler::ON_TASK_FAILED, function (Task $task, Throwable $e) use ($logger) { |
| 66 |
* $logger->error( |
| 67 |
* sprintf('Operation of task %s failed: %s', $task->getName(), $e), |
| 68 |
* ['exception' => $e] |
| 69 |
* ); |
| 70 |
* }); |
| 71 |
*/ |
| 72 |
public const ON_TASK_FAILED = 'task-failed'; |
| 73 |
|
| 74 |
/** |
| 75 |
* Event raised when a {@see Task task} operation is scheduled |
| 76 |
* |
| 77 |
* The task and the {@see DateTime time} when it should run |
| 78 |
* are passed as parameters to the event callbacks. |
| 79 |
* |
| 80 |
* **Example usage:** |
| 81 |
* |
| 82 |
* $scheduler->on($scheduler::ON_TASK_SCHEDULED, function (Task $task, DateTime $dateTime) use ($logger) { |
| 83 |
* $logger->info(sprintf( |
| 84 |
* 'Scheduling task %s to run at %s', |
| 85 |
* $task->getName(), |
| 86 |
* IntlDateFormatter::formatObject($dateTime) |
| 87 |
* )); |
| 88 |
* }); |
| 89 |
*/ |
| 90 |
public const ON_TASK_SCHEDULED = 'task-scheduled'; |
| 91 |
|
| 92 |
/** |
| 93 |
* Event raised upon operation of a {@see Task task} |
| 94 |
* |
| 95 |
* The task and the possibly not yet completed result of the operation as a {@see PromiseInterface promise} |
| 96 |
* are passed as parameters to the event callbacks. |
| 97 |
* |
| 98 |
* **Example usage:** |
| 99 |
* |
| 100 |
* $scheduler->on($scheduler::ON_TASK_OPERATION, function (Task $task, PromiseInterface $_) use ($logger) { |
| 101 |
* $logger->info(sprintf('Task %s operating', $task->getName())); |
| 102 |
* }); |
| 103 |
*/ |
| 104 |
public const ON_TASK_RUN = 'task-run'; |
| 105 |
|
| 106 |
/** |
| 107 |
* Event raised when a {@see Task task} is expired |
| 108 |
* |
| 109 |
* The task and the {@see DateTime expire time} are passed as parameters to the event callbacks. |
| 110 |
* Note that the expiration time is the first time that is considered expired based on the frequency |
| 111 |
* of the task and can be later than the specified end time. |
| 112 |
* |
| 113 |
* **Example usage:** |
| 114 |
* |
| 115 |
* $scheduler->on(Scheduler::ON_TASK_EXPIRED, function (Task $task, DateTime $dateTime) use ($logger) { |
| 116 |
* $logger->info(sprintf( |
| 117 |
* 'Removing expired task %s at %s', |
| 118 |
* $task->getName(), |
| 119 |
* $dateTime->format('Y-m-d H:i:s') |
| 120 |
* )); |
| 121 |
* }); |
| 122 |
*/ |
| 123 |
public const ON_TASK_EXPIRED = 'task-expired'; |
| 124 |
|
| 125 |
/** @var SplObjectStorage<Task, null> The scheduled tasks of this scheduler */ |
| 126 |
protected SplObjectStorage $tasks; |
| 127 |
|
| 128 |
/** |
| 129 |
* Create a new Scheduler |
| 130 |
*/ |
| 131 |
public function __construct() |
| 132 |
{ |
| 133 |
$this->tasks = new SplObjectStorage(); |
| 134 |
|
| 135 |
$this->promises = new SplObjectStorage(); |
| 136 |
$this->timers = new SplObjectStorage(); |
| 137 |
|
| 138 |
$this->init(); |
| 139 |
} |
| 140 |
|
| 141 |
/** |
| 142 |
* Initialize this scheduler |
| 143 |
* |
| 144 |
* @return void |
| 145 |
*/ |
| 146 |
protected function init(): void |
| 147 |
{ |
| 148 |
} |
| 149 |
|
| 150 |
/** |
| 151 |
* Remove and cancel the given task |
| 152 |
* |
| 153 |
* @param Task $task |
| 154 |
* |
| 155 |
* @return $this |
| 156 |
* |
| 157 |
* @throws InvalidArgumentException If the given task isn't scheduled |
| 158 |
*/ |
| 159 |
public function remove(Task $task): static |
| 160 |
{ |
| 161 |
if (! $this->hasTask($task)) { |
| 162 |
throw new InvalidArgumentException(sprintf('Task %s not scheduled', $task->getName())); |
| 163 |
} |
| 164 |
|
| 165 |
$this->cancelTask($task); |
| 166 |
|
| 167 |
$this->tasks->offsetUnset($task); |
| 168 |
|
| 169 |
return $this; |
| 170 |
} |
| 171 |
|
| 172 |
/** |
| 173 |
* Remove and cancel all tasks |
| 174 |
* |
| 175 |
* @return $this |
| 176 |
*/ |
| 177 |
public function removeTasks(): static |
| 178 |
{ |
| 179 |
foreach ($this->tasks as $task) { |
| 180 |
$this->cancelTask($task); |
| 181 |
} |
| 182 |
|
| 183 |
$this->tasks = new SplObjectStorage(); |
| 184 |
|
| 185 |
return $this; |
| 186 |
} |
| 187 |
|
| 188 |
/** |
| 189 |
* Get whether the specified task is scheduled |
| 190 |
* |
| 191 |
* @param Task $task |
| 192 |
* |
| 193 |
* @return bool |
| 194 |
*/ |
| 195 |
public function hasTask(Task $task): bool |
| 196 |
{ |
| 197 |
return $this->tasks->offsetExists($task); |
| 198 |
} |
| 199 |
|
| 200 |
/** |
| 201 |
* Schedule the given task based on the specified frequency |
| 202 |
* |
| 203 |
* @param Task $task |
| 204 |
* @param Frequency $frequency |
| 205 |
* |
| 206 |
* @return $this |
| 207 |
*/ |
| 208 |
public function schedule(Task $task, Frequency $frequency): static |
| 209 |
{ |
| 210 |
$now = new DateTime(); |
| 211 |
if ($frequency->isExpired($now)) { |
| 212 |
return $this; |
| 213 |
} |
| 214 |
|
| 215 |
if ($frequency->isDue($now)) { |
| 216 |
Loop::futureTick(function () use ($task): void { |
| 217 |
$promise = $this->runTask($task); |
| 218 |
$this->emit(static::ON_TASK_RUN, [$task, $promise]); |
| 219 |
}); |
| 220 |
$this->emit(static::ON_TASK_SCHEDULED, [$task, $now]); |
| 221 |
|
| 222 |
if ($frequency instanceof OneOff) { |
| 223 |
return $this; |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
$loop = function () use (&$loop, $task, $frequency): void { |
| 228 |
$promise = $this->runTask($task); |
| 229 |
$this->emit(static::ON_TASK_RUN, [$task, $promise]); |
| 230 |
|
| 231 |
$now = new DateTime(); |
| 232 |
$nextDue = $frequency->getNextDue($now); |
| 233 |
if ($frequency instanceof OneOff || $frequency->isExpired($nextDue)) { |
| 234 |
$removeTask = function () use ($task, $nextDue): void { |
| 235 |
$this->remove($task); |
| 236 |
$this->emit(static::ON_TASK_EXPIRED, [$task, $nextDue]); |
| 237 |
}; |
| 238 |
|
| 239 |
if ($this->promises->offsetExists($task->getUuid())) { |
| 240 |
$pendingPromises = (array) $this->promises->offsetGet($task->getUuid()); |
| 241 |
Promise\all($pendingPromises)->finally($removeTask); |
| 242 |
} else { |
| 243 |
$removeTask(); |
| 244 |
} |
| 245 |
|
| 246 |
return; |
| 247 |
} |
| 248 |
|
| 249 |
$this->attachTimer( |
| 250 |
$task->getUuid(), |
| 251 |
Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $loop) |
| 252 |
); |
| 253 |
$this->emit(static::ON_TASK_SCHEDULED, [$task, $nextDue]); |
| 254 |
}; |
| 255 |
|
| 256 |
$nextDue = $frequency->getNextDue($now); |
| 257 |
$this->attachTimer( |
| 258 |
$task->getUuid(), |
| 259 |
Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $loop) |
| 260 |
); |
| 261 |
$this->emit(static::ON_TASK_SCHEDULED, [$task, $nextDue]); |
| 262 |
|
| 263 |
$this->tasks->offsetSet($task); |
| 264 |
|
| 265 |
return $this; |
| 266 |
} |
| 267 |
|
| 268 |
/** |
| 269 |
* Get whether the given event name is a valid scheduler event |
| 270 |
* |
| 271 |
* @param string $event |
| 272 |
* |
| 273 |
* @return bool |
| 274 |
*/ |
| 275 |
public function isValidEvent(string $event): bool |
| 276 |
{ |
| 277 |
$events = array_flip([ |
| 278 |
static::ON_TASK_CANCEL, |
| 279 |
static::ON_TASK_DONE, |
| 280 |
static::ON_TASK_EXPIRED, |
| 281 |
static::ON_TASK_FAILED, |
| 282 |
static::ON_TASK_RUN, |
| 283 |
static::ON_TASK_SCHEDULED |
| 284 |
]); |
| 285 |
|
| 286 |
return isset($events[$event]); |
| 287 |
} |
| 288 |
|
| 289 |
/** |
| 290 |
* Cancel the timer of the task and all pending operations |
| 291 |
* |
| 292 |
* @param Task $task |
| 293 |
* |
| 294 |
* @return void |
| 295 |
*/ |
| 296 |
protected function cancelTask(Task $task): void |
| 297 |
{ |
| 298 |
Loop::cancelTimer($this->detachTimer($task->getUuid())); |
| 299 |
|
| 300 |
/** @var array<int, PromiseInterface<mixed>> $promises */ |
| 301 |
$promises = $this->detachPromises($task->getUuid()); |
| 302 |
if (! empty($promises)) { |
| 303 |
foreach ($promises as $promise) { |
| 304 |
$promise->cancel(); |
| 305 |
} |
| 306 |
$this->emit(self::ON_TASK_CANCEL, [$task, $promises]); |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
/** |
| 311 |
* Runs the given task immediately and registers handlers for the returned promise |
| 312 |
* |
| 313 |
* @param Task $task |
| 314 |
* |
| 315 |
* @return PromiseInterface<void> |
| 316 |
*/ |
| 317 |
protected function runTask(Task $task): PromiseInterface |
| 318 |
{ |
| 319 |
$promise = $task->run(); |
| 320 |
$this->addPromise($task->getUuid(), $promise); |
| 321 |
|
| 322 |
return $promise->then( |
| 323 |
function ($result) use ($task): void { |
| 324 |
$this->emit(self::ON_TASK_DONE, [$task, $result]); |
| 325 |
}, |
| 326 |
function (Throwable $reason) use ($task): void { |
| 327 |
$this->emit(self::ON_TASK_FAILED, [$task, $reason]); |
| 328 |
} |
| 329 |
)->finally(function () use ($task, $promise): void { |
| 330 |
// Unregister without canceling; the promise is already resolved. |
| 331 |
$this->removePromise($task->getUuid(), $promise); |
| 332 |
}); |
| 333 |
} |
| 334 |
} |