-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_002_delay_amp.php
85 lines (72 loc) · 1.79 KB
/
example_002_delay_amp.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
<?php
use Amp\Deferred;
use Amp\Loop;
use LogicalSteps\Async\Async;
use LogicalSteps\Async\ConsoleLogger;
require __DIR__ . '/../vendor/autoload.php';
function two_seconds(callable $call_back)
{
Loop::delay(
2000,
function () use ($call_back) {
$call_back(null, true);
}
);
}
class Timer
{
public static function delay(int $seconds, callable $call_back)
{
Loop::delay(
$seconds * 1000,
function () use ($call_back) {
$call_back(null, true);
}
);
}
public function wait(int $seconds, callable $call_back)
{
Loop::delay(
$seconds * 1000,
function () use ($call_back) {
$call_back(null, true);
}
);
}
public function hold(int $seconds)
{
yield [$this, 'wait', $seconds];
return true;
}
public function promise(int $seconds)
{
$differed = new Deferred();
Loop::delay(
$seconds * 1000,
function () use ($differed, $seconds) {
$differed->resolve($seconds);
}
);
return $differed->promise();
}
}
function flow()
{
//echo 'started' . PHP_EOL;
yield 'two_seconds';
//echo 'after two seconds' . PHP_EOL;
yield ['Timer', 'delay', 8];
//echo 'after eight seconds' . PHP_EOL;
$timer = new Timer();
yield [$timer, 'wait', 3];
//echo 'after three seconds' . PHP_EOL;
yield $timer->hold(1);
//echo 'after one second' . PHP_EOL;
yield $timer->promise(2);
//echo 'after two seconds' . PHP_EOL;
return yield $timer->hold(7);
}
$async = new Async(new ConsoleLogger());
$async->await(flow());
//$async->await(flow()); //run another session in parallel
Loop::run();