Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time limit function execution in PHP or anything else

I could say that my question is related to PHP, but what I'm more concerned is proper logic of programming in situation where function execution can go on indefinitely.

What is the proper way of monitoring time that it takes to execute some function and how to stop this execution and go on with the rest of the program?

OK, I know that for example there is a set_time_limit() function that returns fatal error but I don't want this, I want my code to just continue after x seconds, or maybe after time exceeded throw an exception, catch it and do something else?

Is writing some kind of a "watchdog" function solution and how is this done?

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

BR, Newman

like image 566
newman555p Avatar asked Sep 27 '11 16:09

newman555p


People also ask

Does PHP have a timeout?

The default timeout is 30 seconds. It can be changed using the max_execution_time php. ini directive or the corresponding php_value max_execution_time Apache httpd.

How can I limit time in PHP?

Use PHP inbuilt function set_time_limit(seconds) where seconds is the argument passed which is the time limit in seconds. It is used, when the user changes the setting outside the php. ini file. The function is called within your own PHP code.

Can we set infinite execution time in PHP?

Yes, it is possible to set an infinite execution time for the PHP Script. We can do it by adding the set_time_limit() function at the beginning of the PHP script.

What is the default execution time set in set_time_limit () in PHP?

The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php. ini . When called, set_time_limit() restarts the timeout counter from zero.


1 Answers

PHP doesn't provide a general way to timeout a function. But many components where this problem is common let you define a timeout.

Examples:

  • The HTTP Stream Wrapper allows you to specify a timeout option:

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

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

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

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

like image 193
NikiC Avatar answered Oct 26 '22 22:10

NikiC