Skip to content

Instantly share code, notes, and snippets.

@alexeyshockov
Created February 25, 2019 15:16
Show Gist options
  • Save alexeyshockov/2765e72cf8af99ce06f57d8d3c3aa32e to your computer and use it in GitHub Desktop.
Save alexeyshockov/2765e72cf8af99ce06f57d8d3c3aa32e to your computer and use it in GitHub Desktop.
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Promise\CancellationException;
use GuzzleHttp\Psr7\Request;
require 'vendor/autoload.php';
$client = new Client();
$requests = function ($total) {
$uri = 'http://ya.ru';
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', $uri);
}
};
$gen = $requests(100);
$pool = new Pool($client, $gen, [
'concurrency' => 5,
'fulfilled' => function ($response, $index, $aggregate) {
static $counter = 0;
echo $response->getStatusCode() . PHP_EOL;
$counter++;
if ($counter >= 10) {
echo "Stopping...\n";
// Stop the execution and cancel all active connections
$aggregate->cancel();
}
},
'rejected' => function ($reason, $index, $aggregate) {
var_dump($reason);
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
try {
// Force the pool of requests to complete.
$promise->wait();
} catch (CancellationException $exception) {
// Do nothing, because cancellation was done by the reason
}
echo "All done\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment