Sunday, November 13, 2011

I wanna exit from a user defined php function if it takes longer time than expected

I think this is common problem that we suffered in our applications. There are many activity in application which took longer time, its shown bad user experience as well as sometime its thrown unexpected errors
like blank page etc.

In php there is no way to judge this thing unless your code is written in multi processing manner.

Let's look on function signature.

function downloadCSV(activityid)
1. is logged-in user (user has proper credits and authenticate user again)
2. RPC to get activity detail (activity is marked as pending/done/in progress etc)
3. RPC to get userids as result from activityid
4. RPC to get user details
5. Make CSV
6. detact credits from user account and update log tables in DB
7. download CSV

This API can fails in various steps.

1. network timeout/failure
2. DB was down
3. Server was down
4. RPC fails because as above reasons
5. Time out due to get user detail
6. DB server was hogged-up

Below i listed, what i figured out from Internet however there are other solutions too but i keep in mind to untouched existing code as less as possible.

1. Check HTTP code using curl

$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
/* Handle 404 here. */

2.  Using curl to set time out time

curl_setopt($curl, CURLOPT_TIMEOUT, 2);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);

3. Provide socket time out settings

ini_set('default_socket_timeout', 10);
$url = "";
if( file_get_contents( urlencode($url) ) === false ) {
   // failure
} else {
   // success

4. Using PHP's stream_set_timeout settings
stream_set_timeout($obj, 2);

Another approaches are forking your code in such manner that it divides in different threads then we can set a timer that will exit after some configurable value.

1 comment:

  1. Code which is given by you is really helpful. It will help to many people.