瀏覽代碼

fix Timer::delay

walkor 3 年之前
父節點
當前提交
f3dc075329
共有 2 個文件被更改,包括 12 次插入9 次删除
  1. 10 7
      src/Events/Event.php
  2. 2 2
      src/Timer.php

+ 10 - 7
src/Events/Event.php

@@ -56,7 +56,7 @@ class Event implements EventInterface
      * Timer id.
      * @var int
      */
-    protected $_timerId = 1;
+    protected $_timerId = 0;
 
     /**
      * Event class name.
@@ -90,8 +90,10 @@ class Event implements EventInterface
     public function delay(float $delay, $func, $args)
     {
         $class_name = $this->_eventClassName;
-        $event = new $class_name($this->_eventBase, -1, $class_name::TIMEOUT, function () use ($func, $args) {
+        $timer_id = $this->_timerId++;
+        $event = new $class_name($this->_eventBase, -1, $class_name::TIMEOUT, function () use ($func, $args, $timer_id) {
             try {
+                $this->deleteTimer($timer_id);
                 $func(...$args);
             } catch (\Throwable $e) {
                 Worker::stopAll(250, $e);
@@ -100,8 +102,8 @@ class Event implements EventInterface
         if (!$event || !$event->addTimer($delay)) {
             return false;
         }
-        $this->_eventTimer[$this->_timerId] = $event;
-        return $this->_timerId++;
+        $this->_eventTimer[$timer_id] = $event;
+        return $timer_id;
     }
 
     /**
@@ -123,7 +125,8 @@ class Event implements EventInterface
     public function repeat(float $interval, $func, $args)
     {
         $class_name = $this->_eventClassName;
-        $event = new $this->_eventClassName($this->_eventBase, -1, $class_name::TIMEOUT | $class_name::PERSIST, function () use ($func, $args) {
+        $timer_id = $this->_timerId++;
+        $event = new $class_name($this->_eventBase, -1, $class_name::TIMEOUT | $class_name::PERSIST, function () use ($func, $args) {
             try {
                 $func(...$args);
             } catch (\Throwable $e) {
@@ -133,8 +136,8 @@ class Event implements EventInterface
         if (!$event || !$event->addTimer($interval)) {
             return false;
         }
-        $this->_eventTimer[$this->_timerId] = $event;
-        return $this->_timerId++;
+        $this->_eventTimer[$timer_id] = $event;
+        return $timer_id;
     }
 
     /**

+ 2 - 2
src/Timer.php

@@ -142,9 +142,9 @@ class Timer
      * @param array $args
      * @return bool|int
      */
-    public function delay(float $delay, $func, $args = [])
+    public static function delay(float $delay, $func, $args = [])
     {
-        return $this->add($delay, $func, $args);
+        return static::add($delay, $func, $args, false);
     }