Repository navigation
Expand file tree
/
Copy pathTimer.php
More file actions
119 lines (99 loc) · 3.24 KB
/
Copy pathTimer.php
File metadata and controls
119 lines (99 loc) · 3.24 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Coordinator;
use Psr\Log\LoggerInterface;
use Throwable;
use function Hyperf\Coroutine\go;
class Timer
{
public const STOP = 'stop';
private array $closures = [];
private int $id = 0;
private static int $count = 0;
private static int $round = 0;
public function __construct(private ?LoggerInterface $logger = null)
{
}
public function after(float $timeout, callable $closure, string $identifier = Constants::WORKER_EXIT): int
{
$id = ++$this->id;
$this->closures[$id] = true;
go(function () use ($timeout, $closure, $identifier, $id) {
try {
++Timer::$count;
$isClosing = match (true) {
$timeout > 0 => CoordinatorManager::until($identifier)->yield($timeout), // Run after $timeout seconds.
$timeout == 0 => CoordinatorManager::until($identifier)->isClosing(), // Run immediately.
default => CoordinatorManager::until($identifier)->yield(), // Run until $identifier resume.
};
if (isset($this->closures[$id])) {
$closure($isClosing);
}
} finally {
unset($this->closures[$id]);
--Timer::$count;
}
});
return $id;
}
public function tick(float $timeout, callable $closure, string $identifier = Constants::WORKER_EXIT): int
{
$id = ++$this->id;
$this->closures[$id] = true;
go(function () use ($timeout, $closure, $identifier, $id) {
try {
$round = 0;
++Timer::$count;
while (true) {
$isClosing = CoordinatorManager::until($identifier)->yield(max($timeout, 0.000001));
if (! isset($this->closures[$id])) {
break;
}
$result = null;
try {
$result = $closure($isClosing);
} catch (Throwable $exception) {
$this->logger?->error((string) $exception);
}
if ($result === self::STOP || $isClosing) {
break;
}
++$round;
++Timer::$round;
}
} finally {
unset($this->closures[$id]);
Timer::$round -= $round;
--Timer::$count;
}
});
return $id;
}
public function until(callable $closure, string $identifier = Constants::WORKER_EXIT): int
{
return $this->after(-1, $closure, $identifier);
}
public function clear(int $id): void
{
unset($this->closures[$id]);
}
public function clearAll(): void
{
$this->closures = [];
}
public static function stats(): array
{
return [
'num' => Timer::$count,
'round' => Timer::$round,
];
}
}