StreamSelectLoop
in package
implements
LoopInterface
A `stream_select()` based event loop.
This uses the stream_select()
function and is the only implementation that works out of the box with PHP.
This event loop works out of the box on PHP 5.4 through PHP 8+ and HHVM.
This means that no installation is required and this library works on all
platforms and supported PHP versions.
Accordingly, the Loop
class and the deprecated Factory
will use this event loop by default if you do not install any of the event loop
extensions listed below.
Under the hood, it does a simple select
system call.
This system call is limited to the maximum file descriptor number of
FD_SETSIZE
(platform dependent, commonly 1024) and scales with O(m)
(m
being the maximum file descriptor number passed).
This means that you may run into issues when handling thousands of streams
concurrently and you may want to look into using one of the alternative
event loop implementations listed below in this case.
If your use case is among the many common use cases that involve handling only
dozens or a few hundred streams at once, then this event loop implementation
performs really well.
If you want to use signal handling (see also addSignal()
below),
this event loop implementation requires ext-pcntl
.
This extension is only available for Unix-like platforms and does not support
Windows.
It is commonly installed as part of many PHP distributions.
If this extension is missing (or you're running on Windows), signal handling is
not supported and throws a BadMethodCallException
instead.
This event loop is known to rely on wall-clock time to schedule future timers
when using any version before PHP 7.3, because a monotonic time source is
only available as of PHP 7.3 (hrtime()
).
While this does not affect many common use cases, this is an important
distinction for programs that rely on a high time precision or on systems
that are subject to discontinuous time adjustments (time jumps).
This means that if you schedule a timer to trigger in 30s on PHP < 7.3 and
then adjust your system time forward by 20s, the timer may trigger in 10s.
See also addTimer()
for more details.
Tags
Table of Contents
Interfaces
Properties
- $futureTickQueue : mixed
- $pcntl : mixed
- $pcntlPoll : mixed
- $readListeners : mixed
- $readStreams : mixed
- $running : mixed
- $signals : mixed
- $timers : mixed
- $writeListeners : mixed
- $writeStreams : mixed
Methods
- __construct() : mixed
- addPeriodicTimer() : TimerInterface
- Enqueue a callback to be invoked repeatedly after the given interval.
- addReadStream() : mixed
- [Advanced] Register a listener to be notified when a stream is ready to read.
- addSignal() : void
- Register a listener to be notified when a signal has been caught by this process.
- addTimer() : TimerInterface
- Enqueue a callback to be invoked once after the given interval.
- addWriteStream() : mixed
- [Advanced] Register a listener to be notified when a stream is ready to write.
- cancelTimer() : void
- Cancel a pending timer.
- futureTick() : void
- Schedule a callback to be invoked on a future tick of the event loop.
- removeReadStream() : mixed
- Remove the read event listener for the given stream.
- removeSignal() : void
- Removes a previously added signal listener.
- removeWriteStream() : mixed
- Remove the write event listener for the given stream.
- run() : void
- Run the event loop until there are no more tasks to perform.
- stop() : void
- Instruct a running event loop to stop.
- streamSelect() : int|false
- Emulate a stream_select() implementation that does not break when passed empty stream arrays.
- waitForStreamActivity() : mixed
- Wait/check for stream activity, or until the next timer is due.
Properties
$futureTickQueue
private
mixed
$futureTickQueue
$pcntl
private
mixed
$pcntl
= false
$pcntlPoll
private
mixed
$pcntlPoll
= false
$readListeners
private
mixed
$readListeners
= array()
$readStreams
private
mixed
$readStreams
= array()
$running
private
mixed
$running
$signals
private
mixed
$signals
$timers
private
mixed
$timers
$writeListeners
private
mixed
$writeListeners
= array()
$writeStreams
private
mixed
$writeStreams
= array()
Methods
__construct()
public
__construct() : mixed
addPeriodicTimer()
Enqueue a callback to be invoked repeatedly after the given interval.
public
addPeriodicTimer(mixed $interval, mixed $callback) : TimerInterface
The second parameter MUST be a timer callback function that accepts the timer instance as its only parameter. If you don't use the timer instance inside your timer callback function you MAY use a function which has no parameters at all.
The timer callback function MUST NOT throw an Exception
.
The return value of the timer callback function will be ignored and has
no effect, so for performance reasons you're recommended to not return
any excessive data structures.
This method returns a timer instance. The same timer instance will also be
passed into the timer callback function as described above.
Unlike addTimer()
, this method will ensure the callback
will be invoked infinitely after the given interval or until you invoke
cancelTimer
.
$timer = $loop->addPeriodicTimer(0.1, function () {
echo 'tick!' . PHP_EOL;
});
$loop->addTimer(1.0, function () use ($loop, $timer) {
$loop->cancelTimer($timer);
echo 'Done' . PHP_EOL;
});
See also example #2.
If you want to limit the number of executions, you can bind arbitrary data to a callback closure like this:
function hello($name, LoopInterface $loop)
{
$n = 3;
$loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) {
if ($n > 0) {
--$n;
echo "hello $name\n";
} else {
$loop->cancelTimer($timer);
}
});
}
hello('Tester', $loop);
This interface does not enforce any particular timer resolution, so special care may have to be taken if you rely on very high precision with millisecond accuracy or below. Event loop implementations SHOULD work on a best effort basis and SHOULD provide at least millisecond accuracy unless otherwise noted. Many existing event loop implementations are known to provide microsecond accuracy, but it's generally not recommended to rely on this high precision.
Similarly, the execution order of timers scheduled to execute at the same time (within its possible accuracy) is not guaranteed.
This interface suggests that event loop implementations SHOULD use a monotonic time source if available. Given that a monotonic time source is only available as of PHP 7.3 by default, event loop implementations MAY fall back to using wall-clock time. While this does not affect many common use cases, this is an important distinction for programs that rely on a high time precision or on systems that are subject to discontinuous time adjustments (time jumps). This means that if you schedule a timer to trigger in 30s and then adjust your system time forward by 20s, the timer SHOULD still trigger in 30s. See also event loop implementations for more details.
Additionally, periodic timers may be subject to timer drift due to re-scheduling after each invocation. As such, it's generally not recommended to rely on this for high precision intervals with millisecond accuracy or below.
Parameters
- $interval : mixed
-
The number of seconds to wait before execution.
- $callback : mixed
-
The callback to invoke.
Return values
TimerInterfaceaddReadStream()
[Advanced] Register a listener to be notified when a stream is ready to read.
public
addReadStream(mixed $stream, mixed $listener) : mixed
Note that this low-level API is considered advanced usage. Most use cases should probably use the higher-level readable Stream API instead.
The first parameter MUST be a valid stream resource that supports
checking whether it is ready to read by this loop implementation.
A single stream resource MUST NOT be added more than once.
Instead, either call removeReadStream()
first or
react to this event with a single listener and then dispatch from this
listener. This method MAY throw an Exception
if the given resource type
is not supported by this loop implementation.
The second parameter MUST be a listener callback function that accepts the stream resource as its only parameter. If you don't use the stream resource inside your listener callback function you MAY use a function which has no parameters at all.
The listener callback function MUST NOT throw an Exception
.
The return value of the listener callback function will be ignored and has
no effect, so for performance reasons you're recommended to not return
any excessive data structures.
If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:
$loop->addReadStream($stream, function ($stream) use ($name) {
echo $name . ' said: ' . fread($stream);
});
See also example #11.
You can invoke removeReadStream()
to remove the
read event listener for this stream.
The execution order of listeners when multiple streams become ready at the same time is not guaranteed.
Parameters
- $stream : mixed
-
The PHP stream resource to check.
- $listener : mixed
-
Invoked when the stream is ready.
addSignal()
Register a listener to be notified when a signal has been caught by this process.
public
addSignal(mixed $signal, mixed $listener) : void
This is useful to catch user interrupt signals or shutdown signals from
tools like supervisor
or systemd
.
The second parameter MUST be a listener callback function that accepts the signal as its only parameter. If you don't use the signal inside your listener callback function you MAY use a function which has no parameters at all.
The listener callback function MUST NOT throw an Exception
.
The return value of the listener callback function will be ignored and has
no effect, so for performance reasons you're recommended to not return
any excessive data structures.
$loop->addSignal(SIGINT, function (int $signal) {
echo 'Caught user interrupt signal' . PHP_EOL;
});
See also example #4.
Signaling is only available on Unix-like platforms, Windows isn't
supported due to operating system limitations.
This method may throw a BadMethodCallException
if signals aren't
supported on this platform, for example when required extensions are
missing.
Note: A listener can only be added once to the same signal, any attempts to add it more than once will be ignored.
Parameters
- $signal : mixed
- $listener : mixed
addTimer()
Enqueue a callback to be invoked once after the given interval.
public
addTimer(mixed $interval, mixed $callback) : TimerInterface
The second parameter MUST be a timer callback function that accepts the timer instance as its only parameter. If you don't use the timer instance inside your timer callback function you MAY use a function which has no parameters at all.
The timer callback function MUST NOT throw an Exception
.
The return value of the timer callback function will be ignored and has
no effect, so for performance reasons you're recommended to not return
any excessive data structures.
This method returns a timer instance. The same timer instance will also be
passed into the timer callback function as described above.
You can invoke cancelTimer
to cancel a pending timer.
Unlike addPeriodicTimer()
, this method will ensure
the callback will be invoked only once after the given interval.
$loop->addTimer(0.8, function () {
echo 'world!' . PHP_EOL;
});
$loop->addTimer(0.3, function () {
echo 'hello ';
});
See also example #1.
If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:
function hello($name, LoopInterface $loop)
{
$loop->addTimer(1.0, function () use ($name) {
echo "hello $name\n";
});
}
hello('Tester', $loop);
This interface does not enforce any particular timer resolution, so special care may have to be taken if you rely on very high precision with millisecond accuracy or below. Event loop implementations SHOULD work on a best effort basis and SHOULD provide at least millisecond accuracy unless otherwise noted. Many existing event loop implementations are known to provide microsecond accuracy, but it's generally not recommended to rely on this high precision.
Similarly, the execution order of timers scheduled to execute at the same time (within its possible accuracy) is not guaranteed.
This interface suggests that event loop implementations SHOULD use a monotonic time source if available. Given that a monotonic time source is only available as of PHP 7.3 by default, event loop implementations MAY fall back to using wall-clock time. While this does not affect many common use cases, this is an important distinction for programs that rely on a high time precision or on systems that are subject to discontinuous time adjustments (time jumps). This means that if you schedule a timer to trigger in 30s and then adjust your system time forward by 20s, the timer SHOULD still trigger in 30s. See also event loop implementations for more details.
Parameters
- $interval : mixed
-
The number of seconds to wait before execution.
- $callback : mixed
-
The callback to invoke.
Return values
TimerInterfaceaddWriteStream()
[Advanced] Register a listener to be notified when a stream is ready to write.
public
addWriteStream(mixed $stream, mixed $listener) : mixed
Note that this low-level API is considered advanced usage. Most use cases should probably use the higher-level writable Stream API instead.
The first parameter MUST be a valid stream resource that supports
checking whether it is ready to write by this loop implementation.
A single stream resource MUST NOT be added more than once.
Instead, either call removeWriteStream()
first or
react to this event with a single listener and then dispatch from this
listener. This method MAY throw an Exception
if the given resource type
is not supported by this loop implementation.
The second parameter MUST be a listener callback function that accepts the stream resource as its only parameter. If you don't use the stream resource inside your listener callback function you MAY use a function which has no parameters at all.
The listener callback function MUST NOT throw an Exception
.
The return value of the listener callback function will be ignored and has
no effect, so for performance reasons you're recommended to not return
any excessive data structures.
If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:
$loop->addWriteStream($stream, function ($stream) use ($name) {
fwrite($stream, 'Hello ' . $name);
});
See also example #12.
You can invoke removeWriteStream()
to remove the
write event listener for this stream.
The execution order of listeners when multiple streams become ready at the same time is not guaranteed.
Some event loop implementations are known to only trigger the listener if
the stream becomes readable (edge-triggered) and may not trigger if the
stream has already been readable from the beginning.
This also implies that a stream may not be recognized as readable when data
is still left in PHP's internal stream buffers.
As such, it's recommended to use stream_set_read_buffer($stream, 0);
to disable PHP's internal read buffer in this case.
Parameters
- $stream : mixed
-
The PHP stream resource to check.
- $listener : mixed
-
Invoked when the stream is ready.
cancelTimer()
Cancel a pending timer.
public
cancelTimer(TimerInterface $timer) : void
See also addPeriodicTimer()
and example #2.
Calling this method on a timer instance that has not been added to this loop instance or on a timer that has already been cancelled has no effect.
Parameters
- $timer : TimerInterface
-
The timer to cancel.
futureTick()
Schedule a callback to be invoked on a future tick of the event loop.
public
futureTick(mixed $listener) : void
This works very much similar to timers with an interval of zero seconds, but does not require the overhead of scheduling a timer queue.
The tick callback function MUST be able to accept zero parameters.
The tick callback function MUST NOT throw an Exception
.
The return value of the tick callback function will be ignored and has
no effect, so for performance reasons you're recommended to not return
any excessive data structures.
If you want to access any variables within your callback function, you can bind arbitrary data to a callback closure like this:
function hello($name, LoopInterface $loop)
{
$loop->futureTick(function () use ($name) {
echo "hello $name\n";
});
}
hello('Tester', $loop);
Unlike timers, tick callbacks are guaranteed to be executed in the order they are enqueued. Also, once a callback is enqueued, there's no way to cancel this operation.
This is often used to break down bigger tasks into smaller steps (a form of cooperative multitasking).
$loop->futureTick(function () {
echo 'b';
});
$loop->futureTick(function () {
echo 'c';
});
echo 'a';
See also example #3.
Parameters
- $listener : mixed
-
The callback to invoke.
removeReadStream()
Remove the read event listener for the given stream.
public
removeReadStream(mixed $stream) : mixed
Removing a stream from the loop that has already been removed or trying to remove a stream that was never added or is invalid has no effect.
Parameters
- $stream : mixed
-
The PHP stream resource.
removeSignal()
Removes a previously added signal listener.
public
removeSignal(mixed $signal, mixed $listener) : void
$loop->removeSignal(SIGINT, $listener);
Any attempts to remove listeners that aren't registered will be ignored.
Parameters
- $signal : mixed
- $listener : mixed
removeWriteStream()
Remove the write event listener for the given stream.
public
removeWriteStream(mixed $stream) : mixed
Removing a stream from the loop that has already been removed or trying to remove a stream that was never added or is invalid has no effect.
Parameters
- $stream : mixed
-
The PHP stream resource.
run()
Run the event loop until there are no more tasks to perform.
public
run() : void
For many applications, this method is the only directly visible invocation on the event loop. As a rule of thumb, it is usually recommended to attach everything to the same loop instance and then run the loop once at the bottom end of the application.
$loop->run();
This method will keep the loop running until there are no more tasks to perform. In other words: This method will block until the last timer, stream and/or signal has been removed.
Likewise, it is imperative to ensure the application actually invokes this method once. Adding listeners to the loop and missing to actually run it will result in the application exiting without actually waiting for any of the attached listeners.
This method MUST NOT be called while the loop is already running.
This method MAY be called more than once after it has explicitly been
stop()
ped or after it automatically stopped because it
previously did no longer have anything to do.
stop()
Instruct a running event loop to stop.
public
stop() : void
This method is considered advanced usage and should be used with care. As a rule of thumb, it is usually recommended to let the loop stop only automatically when it no longer has anything to do.
This method can be used to explicitly instruct the event loop to stop:
$loop->addTimer(3.0, function () use ($loop) {
$loop->stop();
});
Calling this method on a loop instance that is not currently running or on a loop instance that has already been stopped has no effect.
streamSelect()
Emulate a stream_select() implementation that does not break when passed empty stream arrays.
private
streamSelect(array<string|int, mixed> &$read, array<string|int, mixed> &$write, int|null $timeout) : int|false
Parameters
- $read : array<string|int, mixed>
-
An array of read streams to select upon.
- $write : array<string|int, mixed>
-
An array of write streams to select upon.
- $timeout : int|null
-
Activity timeout in microseconds, or null to wait forever.
Return values
int|false —The total number of streams that are ready for read/write. Can return false if stream_select() is interrupted by a signal.
waitForStreamActivity()
Wait/check for stream activity, or until the next timer is due.
private
waitForStreamActivity(int|null $timeout) : mixed
Parameters
- $timeout : int|null
-
Activity timeout in microseconds, or null to wait forever.