-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathReadyScheduler.php
121 lines (105 loc) · 2.66 KB
/
ReadyScheduler.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
<?php
namespace EasySwoole\Component;
use Swoole\Coroutine;
use Swoole\Table;
class ReadyScheduler
{
use Singleton;
const STATUS_UNREADY = 0;
const STATUS_READY = 1;
private $table;
function __construct()
{
$this->table = new Table(2048);
$this->table->column('status',Table::TYPE_INT,1);
$this->table->create();
}
function addItem(string $key,int $status = self::STATUS_UNREADY):ReadyScheduler
{
$this->table->set($key,[
'status'=>$status
]);
return $this;
}
function status(string $key):?int
{
$ret = $this->table->get($key);
if($ret){
return $ret['status'];
}else{
return null;
}
}
function ready(string $key,bool $force = false):ReadyScheduler
{
if($force){
$this->table->set($key,[
'status'=>self::STATUS_READY
]);
}else{
$this->table->incr($key,'status',1);
}
return $this;
}
function unready(string $key,bool $force = false):ReadyScheduler
{
if($force){
$this->table->set($key,[
'status'=>self::STATUS_UNREADY
]);
}else{
$this->table->decr($key,'status',1);
}
return $this;
}
function restore(string $key,?int $status):ReadyScheduler
{
$this->table->set($key,[
'status'=>$status
]);
return $this;
}
function waitReady($keys,float $time = 3.0):bool
{
if(!is_array($keys)){
$keys = [$keys];
}else if(empty($keys)){
return true;
}
while (1){
foreach ($keys as $key => $item){
if($this->status($item) >= self::STATUS_READY){
unset($keys[$key]);
}
if(count($keys) == 0){
return true;
}
if($time > 0){
$time = $time - 0.01;
Coroutine::sleep(0.01);
}else{
return false;
}
}
}
}
function waitAnyReady(array $keys,float $timeout = 3.0):bool
{
if(empty($keys)){
return true;
}
while (1){
foreach ($keys as $key){
if($this->status($key) >= self::STATUS_READY){
return true;
}
}
if($timeout > 0){
$timeout = $timeout - 0.01;
Coroutine::sleep(0.01);
}else{
return false;
}
}
}
}