~/docs
Resonate
Resonate
0.x 0.1.0, current
Fledge Loop
Toggle sidebar
Fledge Loop
webpatser/fledge-loop 0.1.0

Fledge Loop 0.x

Quick Start

Deferred and repeating callbacks, stream readiness, suspensions and signals in a few lines each.

Callbacks run in their own fibers and must return nothing. Loop::run() returns when no enabled, referenced callback is left.

Deferred, delayed and repeating callbacks

use Fledge\Loop;
 
Loop::defer(function () {
echo "deferred\n";
});
 
Loop::delay(0.12, function () {
echo "after 120 ms\n";
});
 
$n = 0;
Loop::repeat(0.05, function (string $id) use (&$n) {
echo 'tick ', ++$n, "\n";
if ($n === 3) {
Loop::cancel($id);
}
});
 
Loop::run(); // returns when nothing referenced is left

Output:

deferred
tick 1
tick 2
after 120 ms
tick 3

Run it on this server

The same callbacks, scheduled inside this request. Each one records its label and the time since the start; Loop::run() returns once the repeat timer is cancelled.

Running...
use Fledge\Loop;

Loop::defer(function () {
    $log('deferred');
});

Loop::delay(0.12, function () {
    $log('after 120 ms');
});

$n = 0;
Loop::repeat(0.05, function (string $id) use (&$n) {
    $log('tick '.++$n);
    if ($n === 3) {
        Loop::cancel($id);
    }
});

Loop::run(); // returns when nothing referenced is left

Wait for a readable stream

use Fledge\Loop;
 
[$reader, $writer] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
stream_set_blocking($reader, false);
 
Loop::onReadable($reader, function (string $id, $stream) {
echo 'got: ', fread($stream, 1024), "\n";
Loop::cancel($id); // cancel before you close
fclose($stream);
});
 
Loop::delay(0.05, function () use ($writer) {
fwrite($writer, 'hello');
});
 
Loop::run();

Warning: Cancel a stream's callbacks before closing the stream. Closing a stream while one of its callbacks is enabled is a programming error.

Suspend and resume a fiber

suspend() parks the calling fiber while the loop keeps running; resume() wakes it with a value.

use Fledge\Loop;
 
function fetch(string $what): string
{
$suspension = Loop::getSuspension();
Loop::delay(0.05, fn () => $suspension->resume("result of $what"));
 
return $suspension->suspend();
}
 
Loop::queue(function () {
echo fetch('A'), "\n";
});
Loop::queue(function () {
echo fetch('B'), "\n";
});
 
Loop::run();

Handle a signal

Needs ext-pcntl; the example also uses posix_kill() from ext-posix to send the signal.

use Fledge\Loop;
 
Loop::onSignal(SIGUSR1, function (string $id) {
echo "got SIGUSR1\n";
Loop::cancel($id); // the last callback gone: the default disposition is back
});
 
Loop::delay(0.05, function () {
posix_kill(getmypid(), SIGUSR1);
});
 
Loop::run();

More complete scripts are on the Examples page; every method is listed in the API Reference.