nrk/predis-async

How can I run a blPop in a continuous loop?

mikegioia opened this issue · 3 comments

I've got the blocking list pop example working from the repo, however, I'm unable to get the blpop working in a continuous loop.

$connection = "tcp://localhost:6379";
$consumer = new \Predis\Async\Client( $connection )
$consumer->connect(
    function ( $consumer ) {
        echo "Connected to Redis, blpop'ing on queue:*\n";
        $consumer->blpop(
            'queue:normal',
            0,
            function ( $response ) use ( $consumer ) {
                list( $priority, $job ) = $response;

                if ( $priority ):
                    $message = "`%s` from channel `%s`.\n";
                    $feedback = sprintf( $message, $job, $priority );
                    echo $feedback;
                endif;

                return TRUE;
            });
    });
$consumer->getEventLoop()->run();

When I run this code with items in the queue, it will process the first one but then halt and hang in the terminal. Is there a way to have this blpop continuously block and then pop an item when it finds one?

As far as I know there's no built in way for this (correct me if I'm wrong), so just put the ->blpop() call inside another method/function and call itself inside the blpop callback.

function process($consumer) {
  $consumer->blpop(
            'queue:normal',
            0,
            function ( $response ) use ( $consumer ) {
                list( $priority, $job ) = $response;

                if ( $priority ):
                    $message = "`%s` from channel `%s`.\n";
                    $feedback = sprintf( $message, $job, $priority );
                    echo $feedback;
                endif;

                process($consumer);
            });
}

$connection = "tcp://localhost:6379";
$consumer = new \Predis\Async\Client( $connection )

$consumer->connect(
    function ( $consumer ) {
       echo "Connected to Redis, blpop'ing on queue:*\n";
       process($consumer);
    }
);
nrk commented

Hi @mikegioia,

like pointed out by @padakuro you need to manually reschedule the BLPOP operation because, unlike commands such as SUBSCRIBE for channels, it blocks only until there's one item available in the list.

Ah, thanks to both of you!