2

I have a function in php and i want set a time out for its work. for example if it's take more than 1second, return false.

function myFucntion()
{
    sleep(2);
    return true;
}

echo myFunction();

I want that these codes return false after one second(for example)!

Sorry for my bad english!

2
  • It would be good to know what kind of functionality you have in mind here. What will it be doing that might take a long time? How will that process react to being interrupted? If the code writes to the database during that time, would you want the timeout to also rollback any updates? There are quite a lot of considerations when doing this kind of thing that you need to think through, and the type of work that the function is doing will strongly influence how you go about achieving this. Commented Dec 5, 2015 at 20:44
  • When I'm faced with this problem, i worked with stream_socket_client and in fread function, if server timeout, my code stuck, first i use thread and then i find stream_set_timeout but this question comes in mind that if this happend again, how can i handle it in general. if timeout time reached, it throw an exeption, i can handle it, but it's just kill the code instantly. Commented Dec 5, 2015 at 21:07

1 Answer 1

1

time() returns current time measured in the number of seconds.

At the beginning of your script set:

$start_time = time();

then later you can get

$current_time = time();

then get diff:

$diff = $current_time - $start_time;

You will get amount of time in seconds that has passed. You can base your logic on that:

if($diff > 5) { // if more than 5 seconds
    // do something, return false etc.
}

More details: http://php.net/manual/en/function.time.php

Sign up to request clarification or add additional context in comments.

4 Comments

This will only check if ($diff > 5) at a specific point in the script. If that check is done after a block (such as a loop, or a sql query) that takes 30 seconds to execute it will not return false after 5 seconds.
@Tristan good point, my solution is quick and easy, although not perfect. Feel free to post your solution, I would vote for it.
Agreed. I can only see it being achieved (maybe) with threading docs.php.net/Thread
I write it with thread now, but thread needs some extension added to php. I search for a way that can use it every where with no limit. if it's not possible... :|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.