Skip to content

Commit 2ac4231

Browse files
committed
[EventLoop] Pass timer signature and associated loop to timer callbacks.
This change allows periodic timers to be easily cancelled in an explicit way from inside their callbacks. Returning FALSE from a callback to cancel the associated timer is no more supported.
1 parent 3194147 commit 2ac4231

3 files changed

Lines changed: 11 additions & 11 deletions

File tree

LibEventLoop.php

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,12 +178,10 @@ protected function addTimerInternal($interval, $callback, $periodic = false)
178178
$timer->signature = spl_object_hash($timer);
179179

180180
$callback = function () use ($timer) {
181-
$rearm = call_user_func($timer->callback);
181+
call_user_func($timer->callback, $timer->signature, $timer->loop);
182182

183-
if ($timer->periodic && $rearm !== false) {
183+
if ($timer->periodic === true) {
184184
event_add($timer->resource, $timer->interval);
185-
} else {
186-
$timer->loop->cancelTimer($timer->signature);
187185
}
188186
};
189187

StreamSelectLoop.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class StreamSelectLoop implements LoopInterface
1717

1818
public function __construct()
1919
{
20-
$this->timers = new Timers();
20+
$this->timers = new Timers($this);
2121
}
2222

2323
public function addReadStream($stream, $listener)

Timer/Timers.php

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,20 @@
22

33
namespace React\EventLoop\Timer;
44

5+
use React\EventLoop\LoopInterface;
6+
57
class Timers
68
{
79
const MIN_RESOLUTION = 0.001;
810

11+
private $loop;
912
private $time;
1013
private $active = array();
1114
private $timers;
1215

13-
public function __construct()
16+
public function __construct(LoopInterface $loop)
1417
{
18+
$this->loop = $loop;
1519
$this->timers = new \SplPriorityQueue();
1620
}
1721

@@ -79,13 +83,11 @@ public function tick()
7983
$timer = $timers->extract();
8084

8185
if (isset($this->active[$timer->signature])) {
82-
$rearm = call_user_func($timer->callback);
86+
call_user_func($timer->callback, $timer->signature, $this->loop);
8387

84-
if ($timer->periodic === true && $rearm !== false) {
88+
if ($timer->periodic === true) {
8589
$timer->scheduled = $timer->interval + $time;
86-
$this->timers->insert($timer, -$timer->scheduled);
87-
} else {
88-
unset($this->active[$timer->signature]);
90+
$timers->insert($timer, -$timer->scheduled);
8991
}
9092
}
9193
}

0 commit comments

Comments
 (0)