I have the following two functions
public function myEndpoint(){
$this->logger->debug('Started');
$this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait')->wait();
$this->logger->debug("I shouldn't wait");
}
public function doNotWait(){
sleep(10);
$this->logger->debug("You shouldn't wait");
}
Now what I need to see in my logs is:
Started
I shouldn't wait
You shouldn't wait
But what I see
Started
You shouldn't wait
I shouldn't wait
Also I tried using the following ways:
Way #1
public function myEndpoint(){
$this->logger->debug('Started');
$this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait', ['synchronous' => false])->wait();
$this->logger->debug("I shouldn't wait");
}
Way #2
public function myEndpoint(){
$this->logger->debug('Started');
$this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait');
$queue = \GuzzleHttp\Promise\queue()->run();
$this->logger->debug("I shouldn't wait");
}
But the result is never the desired one. Any idea? I am using Guzzle 6.x.
Guzzle allows you to send both asynchronous and synchronous requests using the same interface and no direct dependency on an event loop. This flexibility allows Guzzle to send an HTTP request using the most appropriate HTTP handler based on the request being sent.
Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);
If you have a queued job that uses Guzzle to make a request, make sure you set a timeout value for the guzzle request: (new \GuzzleHttp\Client())->get('http://domain.com', [ 'timeout' => 15 ]);
The Asynchronous Request-Response conversation involves the following participants: The Requestor initiates the conversation by sending a Request message amd waits for a Response message. The Provider waits for incoming Request messages and replies with Response messages.
To get it off the unanswered list:
Guzzle does not support "fire and forget" asynchronous requests without deep hacking.
The async methods are abstractions for Client::requestAsync()
, which returns a promise. See https://github.com/guzzle/promises#synchronous-wait - calling Promise::wait()
"is used to synchronously force a promise to complete".
Reference: https://github.com/guzzle/guzzle/issues/1429#issuecomment-197119452
If you don't care about the response, the following should do:
try {
$this->guzzle->post('http://myurl.com/doNotWait', ['timeout' => 1]);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
// do nothing, the timeout exception is intended
}
So, here the request will take 1 sec and the code execution will continue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With