PHP code example of webpatser / fledge-loop

1. Go to this page and download the library: Download webpatser/fledge-loop library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

webpatser / fledge-loop example snippets


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

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();

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();

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();

$pid = Fledge\Loop::fork();          // pcntl_fork() plus afterFork() in the child

// or, around your own pcntl_fork():
$pid = pcntl_fork();
if ($pid === 0) {
    Fledge\Loop::afterFork();        // first thing in the child, from {main}
}

$workers = 0;
while ($workers < $wanted) {
    $suspension = Fledge\Loop::getSuspension();
    Fledge\Loop::delay(0.5, $suspension->resume(...));   // or resume from a signal, timer or socket callback
    $suspension->suspend();                              // back in {main} here
    if (Fledge\Loop::fork() === 0) {
        runWorker();
        exit(0);
    }
    $workers++;
}