-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.php
231 lines (200 loc) · 6.87 KB
/
Timer.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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
<?php declare(strict_types=1);
/**
* @package Localzet Server
* @link https://github.com/localzet/Server
*
* @author Ivan Zorin <[email protected]>
* @copyright Copyright (c) 2018-2024 Localzet Group
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* For any questions, please contact <[email protected]>
*/
namespace localzet;
use Carbon\Carbon;
use localzet\Server\Events\EventInterface;
use localzet\Server\Events\Linux;
use localzet\Server\Events\Revolt;
use RuntimeException;
use Throwable;
use function function_exists;
use function pcntl_alarm;
use function pcntl_signal;
use const PHP_INT_MAX;
use const SIGALRM;
/**
* Таймер
*
* Например:
* localzet\Timer::add($time_interval, callback, array($arg1, $arg2..));
*/
class Timer
{
/**
* Задачи, основанные на сигнале
* [
* run_time => [[$func, $args, $persistent, time_interval],[$func, $args, $persistent, time_interval],..]],
* run_time => [[$func, $args, $persistent, time_interval],[$func, $args, $persistent, time_interval],..]],
* ]
*/
protected static array $tasks = [];
/**
* Событие
*/
protected static ?EventInterface $event = null;
/**
* ID Таймера
*/
protected static int $timerId = 0;
/**
* Статус таймера
* [
* timer_id1 => bool,
* timer_id2 => bool,
* ]
*/
protected static array $status = [];
/**
* Инициализация
*
* @param EventInterface|null $event
*/
public static function init(EventInterface $event = null): void
{
if ($event instanceof EventInterface) {
self::$event = $event;
return;
}
if (function_exists('pcntl_signal')) {
pcntl_signal(SIGALRM, self::signalHandle(...), false);
}
}
/**
* Обработчик сигнала
*/
public static function signalHandle(): void
{
if (!self::$event instanceof EventInterface) {
pcntl_alarm(1);
self::tick();
}
}
/**
* Тик
*/
public static function tick(): void
{
if (empty(self::$tasks)) {
pcntl_alarm(0);
return;
}
$timeNow = Carbon::now()->timestamp;
foreach (self::$tasks as $runTime => $taskData) {
if ($timeNow >= $runTime) {
foreach ($taskData as $index => $oneTask) {
$taskFunc = $oneTask[0];
$taskArgs = $oneTask[1];
$persistent = $oneTask[2];
$timeInterval = $oneTask[3];
try {
$taskFunc(...$taskArgs);
} catch (Throwable $e) {
Server::safeEcho((string)$e);
}
if ($persistent && !empty(self::$status[$index])) {
$newRunTime = Carbon::now()->timestamp + $timeInterval;
if (!isset(self::$tasks[$newRunTime])) {
self::$tasks[$newRunTime] = [];
}
self::$tasks[$newRunTime][$index] = [$taskFunc, (array)$taskArgs, $persistent, $timeInterval];
}
}
unset(self::$tasks[$runTime]);
}
}
}
/**
* Coroutine sleep.
*/
public static function sleep(float $delay): void
{
if (Server::$globalEvent instanceof EventInterface && (Server::$globalEvent instanceof Linux || Server::$globalEvent instanceof Revolt)) {
$suspension = Server::$globalEvent->getSuspension();
static::add($delay, function () use ($suspension): void {
$suspension->resume();
}, null, false);
$suspension->suspend();
}
throw new RuntimeException('Timer::sleep() требует событийную петлю!');
}
/**
* Добавить таймер
*/
public static function add(float $timeInterval, callable $func, null|array $args = [], bool $persistent = true): int
{
if ($timeInterval < 0) {
throw new RuntimeException('$timeInterval не может быть меньше 0');
}
if ($args === null) {
$args = [];
}
if (self::$event instanceof EventInterface) {
return $persistent ? self::$event->repeat($timeInterval, $func, $args) : self::$event->delay($timeInterval, $func, $args);
}
if (!Server::getAllServers()) {
throw new RuntimeException('Таймер может использоваться только в окружении Localzet');
}
if (empty(self::$tasks)) {
pcntl_alarm(1);
}
$runTime = Carbon::now()->timestamp + $timeInterval;
if (!isset(self::$tasks[$runTime])) {
self::$tasks[$runTime] = [];
}
self::$timerId = self::$timerId == PHP_INT_MAX ? 1 : ++self::$timerId;
self::$status[self::$timerId] = true;
self::$tasks[$runTime][self::$timerId] = [$func, $args, $persistent, $timeInterval];
return self::$timerId;
}
/**
* Удалить таймер
*/
public static function del(int $timerId): bool
{
if (self::$event instanceof EventInterface) {
return self::$event->offDelay($timerId);
}
foreach (self::$tasks as $runTime => $taskData) {
if (array_key_exists($timerId, $taskData)) {
unset(self::$tasks[$runTime][$timerId]);
}
}
if (array_key_exists($timerId, self::$status)) {
unset(self::$status[$timerId]);
}
return true;
}
/**
* Удалить все таймеры
*/
public static function delAll(): void
{
self::$tasks = self::$status = [];
if (function_exists('pcntl_alarm')) {
pcntl_alarm(0);
}
self::$event?->deleteAllTimer();
}
}