Sunday 15 July 2012

php - Run Function if Different Function Fails to Complete Within Time Frame -



php - Run Function if Different Function Fails to Complete Within Time Frame -

i have function on website client grabs info live server save locally, didn't expect these local servers aren't in area service, every , script dies after amount of time because failed connect.

i have scheme implemented disable external calls these types of situations, clients can't alternative set "offline mode" begin because service bad , server trying reach live server.

so need do, wrap synctable function function set_time_limit(8) calls different function sets "offline mode" automatically if synctable function fails finish in 8 seconds.

is possible? if so, love know how can save these clients time in areas rough service.

you can accomplish using proc_open, proc_get_status, , proc_terminate start synctable operation process, monitor it, , terminate if necessary. note: may need create simple wrapper script can start synctable function standalone process.

here's function utilize , enforce timeout:

/// executes command , returns output /// if timeout value (in seconds) reached, terminates process /// , returns false function exec_timeout($cmd, $timeout=30) { $descriptors = array( 0 => array('pipe', 'r'), // stdin 1 => array('pipe', 'w'), // stdout 2 => array('pipe', 'w') // stderr ); $pipes = array(); $process = proc_open($cmd, $descriptors, $pipes); $result = ''; $end_time = time() + $timeout; if (is_resource($process)) { // set streams non-blocking stream_set_blocking($pipes[0], 0); stream_set_blocking($pipes[1], 0); stream_set_blocking($pipes[2], 0); $timeleft = $end_time - time(); while ($timeleft > 0) { $status = proc_get_status($process); $result .= stream_get_contents($pipes[1]); // leave loop if process has finished if (!$status['running']) break; $timeleft = $end_time - time(); } if ($timeleft <= 0) { proc_terminate($process); $result = false; } } // check errors $errors = stream_get_contents($pipes[2]); if (!empty($errors)) fwrite(stderr, "$errors\n"); // close streams fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); proc_close($process); homecoming $result; }

php time

No comments:

Post a Comment