amphp

Long running script that polls external server with variable backoff timer?


I am writing a long running script based on Amphp library, that will poll a external server for a list of tasks to run and then execute those tasks.

In the response from the server would be the backoff timer that would control when the script makes it's next request.

Since I am very new to async programming what I am trying is not working.

I tried to create a \Amp\repeat() that had an \Amp\Pause(1000) so that each repeat would pause for 1 second.

Here's my test code:

function test() {
    // http request goes here...

    echo 'server request '.microtime(true).PHP_EOL;

    // based on the server request, change the pause time
    yield new \Amp\Pause(1000);
}

Amp\execute(function () {
    \Amp\onSignal(SIGINT, function () {
        \Amp\stop();
    });

    \Amp\repeat(100, function () {
        yield from test();
    });
});

What I expected to happen was that on each repeat, the test() function would pause for 1 second after the echo but instead the echo was run every 100ms (the repeat time).

In the past I would accomplish this with a while loop and usleep() but since usleep() is blocking this defeats the purpose.

I'm using PHP 7.0 and Amphp from github master branch.


Solution

  • \Amp\repeat calls the callback every 100 milliseconds, regardless of when the callback terminates.

    \Amp\execute(function () {
        /* onSignal handler here for example */
    
        new \Amp\Coroutine(function () {
            while (1) {
                /* dispatch request */
                echo 'server request '.microtime(true).PHP_EOL;
                yield new \Amp\Pause(100);
            }
        });
    });
    

    This is using a normal loop which only continues 100 ms after the last action.

    [If I misunderstood what exactly you want, please note in comments.]