Executing a time limit function in PHP or something else

I could say that my question is related to PHP, but I'm more interested in the correct programming logic in a situation where the execution of a function can continue indefinitely.

What is the correct way to track the time it takes to execute a function, and how to stop this execution and continue working with the rest of the program?

OK, I know that, for example, there is a set_time_limit () function that returns a fatal error, but I donโ€™t want this, I want my code to simply continue after x seconds or, perhaps after exceeding the time, exceed the exception, catch this and do something else?

Writes some kind of solution to the watchdog function and how is this done?

Thank you for any help you can provide, any link, any article that solves this problem in such a way that it should be done.

BR, Newman

+8
php time exception limit
source share
2 answers

PHP does not provide a general way to timeout a function. But many components where this problem is common allow you to determine the timeout.

Examples:

  • HTTP Stream Wrapper allows you to specify the timeout option:

     file_get_contents('http://example.com', false, stream_context_create( array('http' => array('timeout' => 10 /* seconds */)) )); 
  • PDO (database abstraction level) allows you to set a timeout using the PDO::ATTR_TIMEOUT (note that this attribute can mean different things with different database drivers):

     $pdo->setAttribute(PDO::ATTR_TIMEOUT, 10 /* seconds */); 
  • You can set the connection timeout when using FTP :

     $ftp = ftp_connect('example.com', 21, 10 /* seconds */) 

Similarly, all other extensions that have access to potentially remote resources will provide such parameters or timeout parameters.

+3
source share

In PHP in particular, I donโ€™t think you have the right way to control the runtime for your functions from the outside. As you said, things like set_time_limit will throw a Fatar Error and kill your script.

I suggest you save your time from performing your functions using things like microtime() , and throw an exception if the time limit is exceeded; an exception that you can catch outside and continue to act accordingly.

0
source share

All Articles