dq13733519262 2016-06-03 23:54 采纳率: 0%
浏览 96

限制PHP中可调用的执行时间

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.

  • 写回答

1条回答 默认 最新

  • dongya767979565 2016-06-04 00:24
    关注

    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) {
                // ....
            }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题