Can PHP script terminate even if set_time_limit(0) is set?
I am trying to track down what appears to be a very strange bug. I have an application that is structured roughly as follows:
set_time_limit(0);
register_shutdown_function('logScriptCompletion');
function logScriptCompletion() {
log('script completed');
}
log('script started');
// do some calculations periodically printing out progress
The script can take a while to run. The desired behavior is for the script to continue computing to the end even if the stop button is hit or the connection is dropped开发者_JAVA技巧. 99% of the time it works as expected.
Once in a while (maybe once every few months/couple of thousand requests) the calculation does not run all the way through but both "script started" and "script completed" are logged and no other error fatal or otherwise is apparent (I have full logging enabled).
I have a suspicion that this may have something to do with a connection to the server being dropped but have no hard evidence to confirm. I am running Apache 2/PHP 5.2.6 on Linux.
Has anyone else seen a similar issue and can help shed some light on this?
Absolutely! You should also use the ignore_user_abort()
function to make sure.
As a idea, I sometimes think it's a better idea to execute such scripts using the command line version of php from a regularly scheduled cron job. (Otherwise, processing will terminate if httpd is restarted for some reason, etc.)
As such, you'd use the web site to log the fact that you need to run a background processing job (in a database table for example) and upload any data to be processed. The cron executed PHP script would then check for any pending jobs in the database, marking the job as in-progress once it started execution, and then update a 'percentage complete' field in the database table, which the web site could read - hence informing the user of progress.
When processing was complete, PHP would update the database accordingly, marking the job as processed and emailing the user if so desired, etc.
NB: You can usefully extend this approach by adding some basic datetime fields for the start and finish of processing, hence providing a means of trivially checking to see if there are jobs that have been running for a long period of time, etc.
精彩评论