|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Ticker worker |
|
4
|
|
|
* User: moyo |
|
5
|
|
|
* Date: 2018/5/19 |
|
6
|
|
|
* Time: 2:52 PM |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Carno\Monitor\Collector; |
|
10
|
|
|
|
|
11
|
|
|
use Carno\Monitor\Chips\Timers; |
|
12
|
|
|
use Carno\Monitor\Contracts\HMRegistry; |
|
13
|
|
|
use Throwable; |
|
14
|
|
|
|
|
15
|
|
|
class TWorker |
|
16
|
|
|
{ |
|
17
|
|
|
use Timers; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var array |
|
21
|
|
|
*/ |
|
22
|
|
|
private $tasks = []; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param string $id |
|
26
|
|
|
* @param array $metrics |
|
27
|
|
|
* @param callable $worker |
|
28
|
|
|
* @param int $period |
|
29
|
|
|
*/ |
|
30
|
|
|
public function adding(string $id, array $metrics, callable $worker, int $period) : void |
|
31
|
|
|
{ |
|
32
|
|
|
$this->tasks[$this->insert($period, function (string $ik) { |
|
33
|
|
|
$this->running($ik); |
|
34
|
|
|
})][$id] = [$worker, $metrics]; |
|
35
|
|
|
|
|
36
|
|
|
$this->invoking($worker, $metrics); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param string $id |
|
41
|
|
|
*/ |
|
42
|
|
|
public function removing(string $id) : void |
|
43
|
|
|
{ |
|
44
|
|
|
foreach ($this->tasks as $ik => $programs) { |
|
45
|
|
|
if (isset($programs[$id])) { |
|
46
|
|
|
$this->deregistering($programs[$id][1]); |
|
47
|
|
|
unset($this->tasks[$ik][$id]); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
*/ |
|
54
|
|
|
public function stopping() : void |
|
55
|
|
|
{ |
|
56
|
|
|
$this->clearing(function (string $ik) { |
|
57
|
|
|
foreach (array_keys($this->tasks[$ik] ?? []) as $id) { |
|
58
|
|
|
$this->removing($id); |
|
59
|
|
|
} |
|
60
|
|
|
}); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param array $metrics |
|
65
|
|
|
*/ |
|
66
|
|
|
private function deregistering(array $metrics) : void |
|
67
|
|
|
{ |
|
68
|
|
|
array_walk($metrics, function (HMRegistry $registry) { |
|
69
|
|
|
$registry->deregister(); |
|
70
|
|
|
}); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* @param string $ik |
|
75
|
|
|
*/ |
|
76
|
|
|
private function running(string $ik) : void |
|
77
|
|
|
{ |
|
78
|
|
|
$w = $this->tasks[$ik] ?? []; |
|
79
|
|
|
array_walk($w, function (array $stack) { |
|
80
|
|
|
$this->invoking(...$stack); |
|
81
|
|
|
}); |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
/** |
|
85
|
|
|
* @param callable $worker |
|
86
|
|
|
* @param array $metrics |
|
87
|
|
|
*/ |
|
88
|
|
|
private function invoking(callable $worker, array $metrics) : void |
|
89
|
|
|
{ |
|
90
|
|
|
try { |
|
91
|
|
|
call_user_func_array($worker, $metrics); |
|
92
|
|
|
} catch (Throwable $e) { |
|
93
|
|
|
// skip |
|
94
|
|
|
} |
|
95
|
|
|
} |
|
96
|
|
|
} |
|
97
|
|
|
|