2022-12-24 14:36:39 +01:00
|
|
|
<?php declare(strict_types=1);
|
2020-07-21 22:12:34 +02:00
|
|
|
|
|
|
|
require 'vendor/autoload.php';
|
|
|
|
|
2020-07-22 18:18:57 +02:00
|
|
|
use danog\Loop\ResumableLoop;
|
2020-07-21 22:12:34 +02:00
|
|
|
|
|
|
|
use function Amp\delay;
|
|
|
|
|
2020-07-22 18:18:57 +02:00
|
|
|
class MyLoop extends ResumableLoop
|
2020-07-21 22:12:34 +02:00
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Loop name.
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
private $name;
|
|
|
|
/**
|
|
|
|
* Constructor.
|
|
|
|
*
|
|
|
|
* @param string $name Loop name
|
|
|
|
*/
|
2020-07-22 18:18:57 +02:00
|
|
|
public function __construct(string $name)
|
2020-07-21 22:12:34 +02:00
|
|
|
{
|
|
|
|
$this->name = $name;
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Main loop.
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
2022-12-23 20:45:00 +01:00
|
|
|
public function loop()
|
2020-07-21 22:12:34 +02:00
|
|
|
{
|
|
|
|
$number = 0;
|
|
|
|
while (true) {
|
2022-12-23 20:45:00 +01:00
|
|
|
$this->pause(1000);
|
2020-07-21 22:12:34 +02:00
|
|
|
echo "$this: $number".PHP_EOL;
|
2020-07-22 18:18:57 +02:00
|
|
|
$number++;
|
2020-07-21 22:12:34 +02:00
|
|
|
}
|
|
|
|
}
|
2020-07-22 17:46:05 +02:00
|
|
|
|
|
|
|
// Optionally, we can also define logging methods
|
|
|
|
/**
|
|
|
|
* Started loop.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
protected function startedLoop(): void
|
|
|
|
{
|
|
|
|
parent::startedLoop();
|
|
|
|
echo "Started loop $this!".PHP_EOL;
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Exited loop.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
protected function exitedLoop(): void
|
|
|
|
{
|
|
|
|
parent::exitedLoop();
|
|
|
|
echo "Exited loop $this!".PHP_EOL;
|
|
|
|
}
|
|
|
|
// End of logging methods
|
|
|
|
|
2020-07-21 22:12:34 +02:00
|
|
|
/**
|
|
|
|
* Get loop name.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function __toString(): string
|
|
|
|
{
|
|
|
|
return $this->name;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-24 14:36:39 +01:00
|
|
|
$loops = [];
|
|
|
|
for ($x = 0; $x < 10; $x++) {
|
|
|
|
$loop = new MyLoop("Loop number $x");
|
|
|
|
$loop->start();
|
|
|
|
delay(100);
|
|
|
|
$loops []= $loop;
|
|
|
|
}
|
|
|
|
delay(5000);
|
|
|
|
echo "Resuming prematurely all loops!".PHP_EOL;
|
|
|
|
foreach ($loops as $loop) {
|
|
|
|
$loop->resume();
|
|
|
|
}
|