ReactPHP's core reactor event loop that libraries can use for evented I/O.
ReactPHP's core reactor event loop that libraries can use for evented I/O.
ReactPHP's core reactor event loop that libraries can use for evented I/O.
Development version: This branch contains the code for the upcoming v3 release. For the code of the current stable v1 release, check out the
1.xbranch.The upcoming v3 release will be the way forward for this package. However, we will still actively support v1 for those not yet on the latest version. See also installation instructions for more details.
In order for async based libraries to be interoperable, they need to use the
same event loop. This component provides a common LoopInterface that any
library can target. This allows them to be used in the same loop, with one
single run() call that is controlled by the user.
Table of contents
Here is an async HTTP server built with just the event loop.
addPeriodicTimer(0.1, function () {
echo 'Tick' . PHP_EOL;
});
$loop->addTimer(1.0, function () use ($loop, $timer) {
$loop->cancelTimer($timer);
echo 'Done' . PHP_EOL;
});
$loop->run();While the former is more concise, the latter is more explicit. In both cases, the program would perform the exact same steps.
Loop class
(or by manually instantiating any of the loop implementations).Tick every fraction of a second until another
timer stops the periodic timer after a second.Loop class or explicitly with a single run()
call at the end of the program.As of v1.2.0, we highly recommend using the Loop class.
The explicit loop instructions are still valid and may still be useful in some
applications, especially for a transition period towards the more concise style.
The Loop class exists as a convenient global accessor for the event loop.
The Loop class provides all methods that exist on the LoopInterface
as static methods:
If you're working with the event loop in your application code, it's often
easiest to directly interface with the static methods defined on the Loop class
like this:
use React\EventLoop\Loop;
$timer = Loop::addPeriodicTimer(0.1, function () {
echo 'Tick' . PHP_EOL;
});
Loop::addTimer(1.0, function () use ($timer) {
Loop::cancelTimer($timer);
echo 'Done' . PHP_EOL;
});On the other hand, if you're familiar with object-oriented programming (OOP) and
dependency injection (DI), you may want to inject an event loop instance and
invoke instance methods on the LoopInterface like this:
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
class Greeter
{
private $loop;
public function __construct(LoopInterface $loop)
{
$this->loop = $loop;
}
public function greet(string $name)
{
$this->loop->addTimer(1.0, function () use ($name) {
echo 'Hello ' . $name . '!' . PHP_EOL;
});
}
}
$greeter = new Greeter(Loop::get());
$greeter->greet('Alice');
$greeter->greet('Bob');Each static method call will be forwarded as-is to the underlying event loop
instance by using the Loop::get() call internally.
See LoopInterface for more details about available methods.
When using the Loop class, it will automatically execute the loop at the end of
the program. This means the following example will schedule a timer and will
automatically execute the program until the timer event fires:
use React\EventLoop\Loop;
Loop::addTimer(1.0, function () {
echo 'Hello' . PHP_EOL;
});As of v1.2.0, we highly recommend using the Loop class this way and omitting any
explicit run() calls. For BC reasons, the explicit run()
method is still valid and may still be useful in some applications, especially
for a transition period towards the more concise style.
If you don't want the Loop to run automatically, you can either explicitly
run() or stop() it. This can be useful if you're using
a global exception handler like this:
use React\EventLoop\Loop;
Loop::addTimer(10.0, function () {
echo 'Never happens';
});
set_exception_handler(function (Throwable $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
Loop::stop();
});
throw new RuntimeException('Demo');The get(): LoopInterface method can be used to
get the currently active event loop instance.
This method will always return the same event loop instance throughout the lifetime of your application.
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
$loop = Loop::get();
assert($loop instanceof LoopInterface);
assert($loop === Loop::get());This is particularly useful if you're using object-oriented programming (OOP)
and dependency injection (DI). In this case, you may want to inject an event
loop instance and invoke instance methods on the LoopInterface like this:
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
class Greeter
{
private $loop;
public function __construct(LoopInterface $loop)
{
$this->loop = $loop;
}
public function greet(string $name)
{
$this->loop->addTimer(1.0, function () use ($name) {
echo 'Hello ' . $name . '!' . PHP_EOL;
});
}
}
$greeter = new Greeter(Loop::get());
$greeter->greet('Alice');
$greeter->greet('Bob');See LoopInterface for more details about available methods.
In addition to the LoopInterface, there are a number of
event loop implementations provided.
All of the event loops support these features:
For most consumers of this package, the underlying event loop implementation is
an implementation detail.
You should use the Loop class to automatically create a new instance.
Advanced! If you explicitly need a certain event loop implementation, you can
manually instantiate one of the following classes.
Note that you may have to install the required PHP extensions for the respective
event loop implementation first or they will throw a BadMethodCallException on creation.
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 any PHP version.
This means that no installation is required and this library works on all
platforms and supported PHP versions.
Accordingly, the Loop class 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 run();
…php $loop->addTimer(3.0, function () use ($loop) { $loop->stop(); });
…php $loop->addTimer(0.8, function () { echo 'world!' . PHP_EOL; });
$loop->addTimer(0.3, function () { echo 'hello '; });
See also [example #1](examples).
If you want to access any variables within your callback function, you
can bind arbitrary data to a callback closure like this:
```php
function hello($name, LoopInterface $loop)
{
$loop->addTimer(1.0, function () use ($name) {
echo "hello $name\n";
});
}
hello('Tester', $loop);
…
php
$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);
…
php
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(functionNo open issues yet, or sync has not completed.