开发者

Email on separate thread in php

I'm wondering if there is a way to start a separate thread in php to send and email. I have a small web service which takes some information from an iPad app and then inserts data into a db and sends an email afterwards. The problem is that sometimes the email takes too long to send and the iPad's request times out. Is there a way I could send开发者_开发问答 the email on separate thread? I basically want to tell the iPad everything was successful before the email sends.

Some example code:

... Process info and insert into DB
echo "success"; //this should be returned to the iPad right away.

//start new thread here or possibly fork???
$email->send();

Thanks!


As pointed out, PHP doesn't have multithreading abilities, but it does have multi-processing functionality. You can create and call a second PHP that the first one would call to process the email. This script would need to be able to run on the command line.

exec('nohup php emailscript.php >/dev/null 2>&1 &');

It is very important to have the nohup, and everything after it. What that is doing is putting the process in the background and redirecting all output. Otherwise PHP will wait for it to finish and return something. The nohup will make sure the script isn't killed by the OS when the parent calling process ends.

You do need to somehow pass the email information to the script. You can put the information in a database and pass it a record ID, pass the information as parameters, or a number of other options.


I believe you want to execute an ob_flush() to send the data back to the client and allow your PHP script to continue executing. Note that you must be done with sending things back to the client, as you can't send any more after the ob_flush().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜