I am currently trying to generate an epub on demenad from content that is available to me. Unfortunately, when there is alot of content for the epub, it takes a while (10 mins in some cases) for the http request to complete - which is not ideal
I want to follow an approach similar to that of Safari - Generate an epub and email the user when the document is available
My question is - what is the best way for running a background task/thread in PHP that could take a long time to complete
You want to be careful with long-running PHP processes as, for one PHP is not very memory efficient (as an example an array of just 100 ints in PHP can consume as much as 15KB of memory). This is normally fine for 99% of the use cases since most people are just using PHP for websites and those processes run for fractions of a second so memory is sacrificed for speed. However, for a long-running process (especially if you have a lot of them) this may not be your best solution.
You also want to be very careful calling exec/shell_exec like functions in PHP as they are internally implemented as streams (i.e. they can cause blocking in the parent process as it normally has to wait on the stream to return data).
One option to background the task is to use fork. However, I strongly suggest using a proper job manager like gearman (see php extensions also), or queue, like amqp or zmq, to handle these tasks more cleanly. Which one is more suitable for your use case, I'll let you decide.
you can run the command
$command = 'nohup >/dev/null 2>&1 /your/background/script.php &'
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