Limit execution time of an function or command PHP [duplicate]
Asked Answered
D

7

23

Hi is there a possibility to set time limit only to a command or only to a function eg:

function doSomething()
{
    //..code here..

    function1();

    //.. some code here..

}

I want to set time limit only to function1.

There exits set_time_limit but I think this sets the time limit to whole script. Anybody any Idea?

Demisec answered 24/7, 2009 at 8:57 Comment(1)
What do you want to happen if the timer expires while function1 is still running?Deyoung
I
23

set_time_limit() does run globally, but it can be reset locally.

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. 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. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

I've not tested it, but you may be able to set it locally, resetting when you leave the

<?php
set_time_limit(0);  // global setting

function doStuff()
{
    set_time_limit(10);   // limit this function
    //  stuff
    set_time_limit(10);   // give ourselves another 10 seconds if we want
    //  stuff
    set_time_limit(0);    // the rest of the file can run forever
}

// ....
sleep(900);
// ....
doStuff();  // only has 10 secs to run
// ....
sleep(900);
// ....

set_time_limit() ... Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

Inefficient answered 24/7, 2009 at 9:13 Comment(5)
Very nice! thanx! but it returns a fatal error if the time criteria was not met. Is there a way to avoid that.Demisec
It's not possible to stop the fatal error - as that is what the timeout is. If you want to do something else, then you will have to define more fully what you are doing, and design a system that will perform as required. If you are doing database queries that are taking too long, I would try to improve the query (and underlying DB) to speed them up, rather than trying to fix somethough outside the original problem.Inefficient
Thanx you helped me find the right thing. I think what I was looking was max_input_time Do you know if it returns also fatal error if the deadline is not met?Demisec
the php.ini config, max_input_time, is how long a script takes to start-up, parsing input data, like POST, GET and file uploads. These tasks must completed before any of your PHP code is run.Inefficient
not good solution, cause it affected globally to all scripts, so better use timeouts !Ora
L
12

You would need to code that yourself if you want function1 to return when the time limit is up.

function doStuff($seconds)
{
    $finish=time()+$seconds;

    $done=false;
    $timeout=false;

    while (!$done && !$timeout)
    {
        //do stuff here, set $done to true if you complete

        //out of time?
        $timeout=time() >= $finish;

    }

    return $done; //let caller know if we completed
}

Of course, the "stuff" that you do needs to be iterative so that you can keep checking on your elapsed time and quit if necessary.

If you want timeout execution of an arbitrary function and have control returned to you, that is not supported. If you really need to do this, engineer it as a separate process. Then you can close the process if it seems to be taking too long.

Loft answered 24/7, 2009 at 9:0 Comment(5)
Thanx for the answer but look at this acenario function doStuff($seconds) { $finish=time()+$seconds; $done=false; $timeout=false; while (!$done && !$timeout) { //do stuff here, set $done to true if you complete //out of time? $result = anotherFunction(); this function is a standart php function which can not be modified and it takes too much to execute in my case. $timeout=time() >= $finish; } return $done; //let caller know if we completed }Demisec
Thanx for the answer but look at this acenario <code> function doStuff($seconds) { $finish=time()+$seconds; $done=false; $timeout=false; while (!$done && !$timeout) { //do stuff here, set $done to true if you complete //out of time? $result = anotherFunction(); this function is a standart php function which can not be modified and it takes too much to execute in my case. $timeout=time() >= $finish; } return $done; //let caller know if we completed }</code>Demisec
You can't have an arbitrary function quit after a specified time. If you really need to do this, engineer it as a separate process. Then you can close the process if it seems to be taking too long.Loft
Well, you can do this in basically any other language. Another glorious "feature" of PHP ...Secretion
didnot work for me php v7.2.3 , if "do stuff here" takes too much time, other part didnot trigged untill 'doing' will not end of all freezed ! not worked solution (Ora
T
6
$endtime=time()+10;

while(time()!=$endtime){

    echo ".";
}
Terrorism answered 22/9, 2014 at 22:33 Comment(0)
I
3

No, it is not possible : max_execution_time is used as a security measure, to avoid having buggy scripts (like infinite loop) destroy the server ; but it is not intended to work on a function-unit basis.

And the fact that it ends up with a Fatal Error is definitly not nice for the user anyway...

Impermanent answered 24/7, 2009 at 10:35 Comment(0)
T
1

I use exec to run shellscript that generates export from external application. If script runs too long, max_execution_time is reached and user will never know what happened. Limitation to such function would help me determine if end is near and send some user friendly error.

Territory answered 3/8, 2009 at 4:39 Comment(0)
O
1

in windows, for some reason each call to mail() restart "set_time_limit"

you can run:

<?php
set_time_limit(5);
// then with mail server OFF eat ALL time:
    for($i = 0; $i < 999; ++ $i)if(!@mail('[email protected]', 'test', time()))echo microtime(true)."\n";

and NEVER you will get "PHP Fatal error: Maximum execution time of 5 seconds exceeded"

Orthodontia answered 22/6, 2022 at 21:46 Comment(0)
O
0

i dont think that this is possible, but why would you do this? If a script ever gets interrupted i might not do want you want it to. This should be more like a protection from yourself (just in case you upload an endless loop or something that will take hours), but if your script takes lots of time, you should either give it the time that it takes, or change the script so that it runs faster (for some crons its ok to take a while, but if a normal script that is called quite often takes more then the default time limit, you might face some serious performance problems)

Omnidirectional answered 24/7, 2009 at 9:2 Comment(2)
Lets say that my scripts gets data from database and for each row it tries to do something with that row like doSomething(row) but sometimes this could be too much time consuming. So I need something like when this doSomething is not finished in 5 minutes to continue with the other row. If somehow I could make a function like : function doSomething() { //code here return results; } But if this function can not be completed in 5 minutes to return false for example!Demisec
ah ok, in that case stick with the answer of paul dixonOmnidirectional

© 2022 - 2024 — McMap. All rights reserved.