What I'm trying to do is this: User makes an API call, I give the response, and then I start doing actions that take long such as sending emails. (Emails take long because I'm using SMTP, so swiftmailer does that in a synchronous way.)
According to the documentation finish() should be called after the response has been sent. When I test this however, this seems to be not the case. My client side stays waiting until the finish() is done.
Server side code:
$app = new Silex\Application();
$app->get('/hello', function (Request $r) use($app) {
return $app->json("I should load within a few milliseconds.");
});
$app->finish(function() use () {
//Pretend to do some slow action afterwards
sleep(5);
});
$app->run();
Now if I load the page http://localhost/hello
it will take 5 seconds for it to load. While my expectation is that it would load instantaneous. Am I misunderstanding the documentation?
Update:
Technically The accepted answer did what I asked for it. Practically I found a different solution:
I was looking for a way to get my emails sent in a way that the end-user wouldn't have to wait for it. For my purposes I switched over to using Swift_MailTransport
instead of Swift_SmtpTransport
, and configured exim4 locally as a smarthost. This way the email gets handed off to Exim4 and the script continues immediately.
If you are looking for other long processes to execute than just emails, have a look at message queues such as Beanstalk, I read great things about them.
The accepted answer below does work (also follow the links in the comments to the documentation page), but I found the solution not clean enough for my particular situation.