Skip to content

Loop terminates when sleep time is reached #49

Closed

Description

@bcremer

When calling Clue\React\Block\sleep within a HTTP Server loop the loop terminates after the timeout

Repo

$ cat composer.json 
{
    "require": {
        "react/http": "^1.0",
        "clue/block-react": "^1.3"
    }
}
<?php

use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;

use function Clue\React\Block\sleep;

require __DIR__ . '/vendor/autoload.php';

$loop = React\EventLoop\Factory::create();

$server = new React\Http\Server($loop, static function (ServerRequestInterface $request) use ($loop) {
    $duration = 1.5;
    echo sprintf("Sleeping for %F\n", $duration);
    sleep(1.5, $loop);
    echo "After Sleep";

    return new Response(200, [], 'Some reponse');
});

$socket = new React\Socket\Server('127.0.0.1:8080', $loop);
echo "Server running at http://127.0.0.1:8080\n";

$server->listen($socket);
$loop->run();
$ php repro.php
Server running at http://127.0.0.1:8080
Sleeping for 1.500000
After Sleep%    # process terminated
$ curl  "http://localhost:8080/"
curl: (52) Empty reply from server

When the call to sleep is removed the loop does not exit like expected:

$ php repro.php
Server running at http://127.0.0.1:8080
$ curl  "http://localhost:8080/"                                                   
Some reponse%
$ curl  "http://localhost:8080/"
Some reponse%      

Activity

  1. bcremer commented on Jul 27, 2020

    @bcremer
    Author
  2. added
    questionFurther information is requested
    on Aug 1, 2020
  3. clue commented on Aug 1, 2020

    @clue
    Owner

    @bcremer Already answered via the referenced Twitter thread, but thanks for asking here anyway!

    This has been discussed in #20, #44 and others before and this is more or less by design.

    As a rule of thumb, mixing blocking and non-blocking code should be avoided. This means these functions should only be used in a blocking application. If you're using a non-blocking application, you should use non-blocking primitives provided by promises and event emitters.

    In your case this means that $loop->addTimer() should be used instead of a blocking sleep().

    I hope this helps 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions