public
Last active

  • Download Gist
no_deferred.php
PHP
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
<?php
 
require_once './vendor/autoload.php';
 
abstract class Element
{
protected $loop;
public $active = false;
 
public function __construct(\React\EventLoop\LoopInterface $loop)
{
$this->loop = $loop;
}
 
abstract public function synchronize();
}
 
class A extends Element
{
 
public function synchronize()
{
$this->active = true;
echo 'Processing A ...'.PHP_EOL;
for ($i = 1; $i <= 7; $i++) {
echo date('H:i:s').'| $A: '.$i.PHP_EOL;
sleep(1);
}
echo 'Finished processing A ...'.PHP_EOL;
$this->active = false;
}
}
 
class B extends Element
{
public function synchronize()
{
$this->active = true;
echo 'Processing B ...'.PHP_EOL;
for ($i = 1; $i <= 5; $i++) {
echo date('H:i:s').'| $B: '.$i.PHP_EOL;
sleep(1);
}
echo 'Finished processing B ...'.PHP_EOL;
$this->active = false;
}
}
 
class Test
{
protected $loop;
public $a;
public $b;
 
public function __construct()
{
$this->loop = React\EventLoop\Factory::create();
$this->deferred = new \React\Promise\Deferred();
$this->promise = $this->deferred->promise();
 
$this->a = new A($this->loop);
$this->b = new B($this->loop);
}
 
public function run()
{
$that = $this;
 
$this->loop->addPeriodicTimer(1, function ($timer) {
echo '.'.PHP_EOL;
});
 
$this->loop->addTimer(5, function ($timer) use ($that) {
echo 'run a'.PHP_EOL;
$that->a->synchronize();
});
$this->loop->addTimer(3, function ($pTimer) use ($that) {
echo 'run b'.PHP_EOL;
$that->b->synchronize();
});
 
$this->loop->addTimer(6, function ($pTimer) use ($that) {
echo 'run b once more'.PHP_EOL;
$that->b->synchronize();
});
 
$this->loop->run();
}
}
 
$test = new Test();
$test->run();
output_log.txt
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
.
.
run b
Processing B ...
13:58:27| $B: 1
13:58:28| $B: 2
13:58:29| $B: 3
13:58:30| $B: 4
13:58:31| $B: 5
Finished processing B ...
.
.
run a
Processing A ...
13:58:33| $A: 1
13:58:34| $A: 2
13:58:35| $A: 3
13:58:36| $A: 4
13:58:37| $A: 5
13:58:38| $A: 6
13:58:39| $A: 7
Finished processing A ...
run b once more
Processing B ...
13:58:40| $B: 1
13:58:41| $B: 2
13:58:42| $B: 3
13:58:43| $B: 4
13:58:44| $B: 5
Finished processing B ...
.
.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.