1
0
mirror of https://github.com/danog/loop.git synced 2024-12-02 17:27:48 +01:00
loop/examples/2. Advanced/ResumableLoop.php

90 lines
1.6 KiB
PHP
Raw Normal View History

2020-07-21 22:12:34 +02:00
<?php
require 'vendor/autoload.php';
use Amp\Loop as AmpLoop;
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
*/
public function loop(): \Generator
{
$number = 0;
while (true) {
2020-07-22 18:18:57 +02:00
yield $this->pause(1);
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.
*
* @return void
*/
protected function startedLoop(): void
{
parent::startedLoop();
echo "Started loop $this!".PHP_EOL;
}
/**
* Exited loop.
*
* @return void
*/
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.
*
* @return string
*/
public function __toString(): string
{
return $this->name;
}
}
AmpLoop::run(function () {
$loops = [];
for ($x = 0; $x < 10; $x++) {
2020-07-22 18:18:57 +02:00
$loop = new MyLoop("Loop number $x");
2020-07-21 22:12:34 +02:00
$loop->start();
yield delay(100);
$loops []= $loop;
}
2020-07-22 18:18:57 +02:00
yield delay(5000);
echo "Resuming prematurely all loops!".PHP_EOL;
foreach ($loops as $loop) {
$loop->resume();
}
2020-07-21 22:12:34 +02:00
});