A little background: I have a PHP site (Drupal 7/Linux/Apache) where users can run very intensive reports (lots of PHP calculations and MySQL queries). When they do this, it can take up to 10-15 minutes to complete.
Today, I had the server stop responding and start giving "timeout" messages, and AWS Lightsail (where it is hosted) registered an instance status error. It appeared to happen while a user was running such a report. In the end I had to reboot the server.
My question is this: if I periodically introduce a PHP sleep() or usleep() during the report generation, does that "pause" my script and allow the server to do other things, thereby mitigating timeouts? Or would the sleep() command simply make things worse?
It isn't clear from the PHP documentation if sleep() makes room for other processes on the server to run.
Thanks for any insights.
=== UPDATE: ===
After more digging and such, it seems that my problem had to do with Apache taking up too much RAM per worker thread, partly because PHP's memory limit was high, and partly because I was storing lots of information in the $_SESSION for each query result of the report.
I did try introducing usleep commands randomly (eg, if rand(0, 100) == 25 then usleep...) but honestly, it didn't seem to help with the problem of the system running out of RAM.
In the end, I decided to just keep appending the report data to a text file on the server (not accessible from the web), rather than storing in the $_SESSION. This made the reports run MUCH faster. 20 seconds instead of 10 minutes. And I have a little cron job that looks for those text files older than XX minutes and deletes them.
It's a klugey hack, I know, but it gets the job done and keeps the RAM usage to a reasonable level.
The sleep() or usleep() functions just pause the script execution for the specified amount of time. During that time, other processes on the server can run, but PHP itself won't be doing anything useful.
If the reason for the timeouts is due to a lack of resources on the server (such as CPU or memory), then introducing sleep() calls may help mitigate the issue. By pausing your script, you're allowing other processes to run and free up resources for your script to continue.
However, if the reason for the timeouts is due to a slow or inefficient script, introducing sleep() calls won't help. In fact, it will make the situation worse by prolonging the time it takes for your script to complete.
If you want to reduce the execution time, then you should look for some database and code optimizations.