0

I need a function that will throw a catchable exception after a callable function has taken to long to complete it's task.

Note: I am not referring to the max execution time for a PHP script.

The function should work like the call_user_func except that it takes a time limit in seconds for the callable.

    function task() {
        // does a lot of work...
    }

    try {
       call_user_func('task', 30); // limit to 30 seconds
    } catch (TimeoutException $ex) {
        // ....
    }

I can not add custom logic to the task function to throw an exception on it's own. The idea is to force the callable methods to abort or fail after X number of seconds.

I have CLI scripts that I want to regulate how long they take to complete a task.

Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • 1
    [This question](http://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications) might give you some hints. Implementing your own scheduler is by no means trivial though, lots of edge cases to take into consideration generally. – ccKep Jun 04 '16 at 00:16

1 Answers1

0

You could use EvTimer. However, you have to install the Ev Package since it's not part of PHP. You can do that with pecl install ev

    <?php

        function task(){
            // DOES A LOT OF WORK...
        }

        function runTaskWithin($seconds) {
            // SET UP A TIMER TO FIRE AFTER X-SECONDS
            $evT = new EvTimer($seconds, 0, function ($seconds) {
                throw(new Exception("{$seconds} Seconds has elapsed since Execution began... Better rest, Now."));
            });
        }

        // ONCE 30 SECONDS PASSES A NEW EXCEPTION WILL BE THROWN...
        // NON-BLOCKING... 
        try {
            runTaskWithin(30); //  LIMIT TO 30 SECONDS
        } catch (Exception $ex) {
            // ....
        }
Poiz
  • 7,611
  • 2
  • 15
  • 17
  • 1
    1) OP mentioned he cannot edit the task method 2) By the examples in the php docs it looks like EvTimer is a blocking function. Which means your example would just always sleep 30 seconds and throw an exception? – ccKep Jun 04 '16 at 00:49