| 1 | <?php |
||
| 16 | trait TimersAware |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * Array of timers. |
||
| 20 | * |
||
| 21 | * @var TimerInterface[] |
||
| 22 | */ |
||
| 23 | private $timers = []; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @var array |
||
| 27 | */ |
||
| 28 | private $reactTimers = []; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * Add one timer. |
||
| 32 | * |
||
| 33 | * @param TimerInterface $timer |
||
| 34 | */ |
||
| 35 | public function addTimer(TimerInterface $timer) |
||
| 36 | { |
||
| 37 | $eventLoop = $this->getEventLoop(); |
||
| 38 | if ($timer->isPeriodic()) { |
||
| 39 | $reactTimer = $eventLoop->addPeriodicTimer($timer->getInterval(), $timer); |
||
| 40 | } else { |
||
| 41 | $reactTimer = $eventLoop->addTimer($timer->getInterval(), $timer); |
||
| 42 | } |
||
| 43 | $this->timers[] = $timer; |
||
| 44 | $this->reactTimers[spl_object_hash($timer)] = $reactTimer; |
||
| 45 | } |
||
| 46 | |||
| 47 | /** |
||
| 48 | * Cancel Timer. |
||
| 49 | * |
||
| 50 | * @param TimerInterface $timer |
||
| 51 | */ |
||
| 52 | public function cancelTimer(TimerInterface $timer) |
||
| 53 | { |
||
| 54 | $id = spl_object_hash($timer); |
||
| 55 | if (isset($this->reactTimers[$id])) { |
||
| 56 | $this->getEventLoop()->cancelTimer($this->reactTimers[$id]); |
||
| 57 | } |
||
| 58 | } |
||
| 59 | |||
| 60 | /** |
||
| 61 | * @return TimerInterface[] |
||
| 62 | */ |
||
| 63 | public function getTimers() |
||
| 64 | { |
||
| 65 | return $this->timers; |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Gets the loop instance. |
||
| 70 | * |
||
| 71 | * @return LoopInterface |
||
| 72 | */ |
||
| 73 | abstract public function getEventLoop(); |
||
| 74 | } |