13declare(strict_types=1);
15namespace pocketmine\snooze;
17use pmmp\thread\ThreadSafeArray;
19use
function microtime;
30 private readonly ThreadSafeArray $sharedObject;
36 private array $handlers = [];
38 private int $nextSleeperId = 0;
40 public function __construct(){
41 $this->sharedObject =
new ThreadSafeArray();
49 $id = $this->nextSleeperId++;
51 $this->handlers[$id] = $handler;
62 unset($this->handlers[$notifierId]);
65 private function sleep(
int $timeout) : void{
66 $this->sharedObject->synchronized(function() use ($timeout) : void{
67 if($this->sharedObject->count() === 0){
68 $this->sharedObject->wait($timeout);
79 $this->processNotifications();
81 $sleepTime = (int) (($unixTime - microtime(
true)) * 1000000);
83 $this->sleep($sleepTime);
96 $this->processNotifications();
104 $notifierIds = $this->sharedObject->synchronized(
function() : array{
106 foreach($this->sharedObject as $notifierId => $_){
107 $notifierIds[$notifierId] = $notifierId;
108 unset($this->sharedObject[$notifierId]);
112 if(count($notifierIds) === 0){
115 foreach($notifierIds as $notifierId){
116 if(!isset($this->handlers[$notifierId])){
120 $this->handlers[$notifierId]();
removeNotifier(int $notifierId)
sleepUntil(float $unixTime)
addNotifier(\Closure $handler)