Invoker

EasySwoole为了让框架支持函数超时处理和swoole1.x与2.x,封装了一个Invoker。

实现代码

  1. namespace EasySwoole\Core\Component;
  2. use EasySwoole\Core\Swoole\ServerManager;
  3. use \Swoole\Process;
  4. use \Swoole\Coroutine;
  5. class Invoker
  6. {
  7. /*
  8. * Async::set([
  9. 'enable_signalfd' => false,
  10. ]);
  11. */
  12. public static function exec(callable $callable,$timeOut = 100 * 1000,...$params)
  13. {
  14. pcntl_async_signals(true);
  15. pcntl_signal(SIGALRM, function () {
  16. Process::alarm(-1);
  17. throw new \RuntimeException('func timeout');
  18. });
  19. try
  20. {
  21. Process::alarm($timeOut);
  22. $ret = self::callUserFunc($callable,...$params);
  23. Process::alarm(-1);
  24. return $ret;
  25. }
  26. catch(\Throwable $throwable)
  27. {
  28. throw $throwable;
  29. }
  30. }
  31. public static function callUserFunc(callable $callable,...$params)
  32. {
  33. if(ServerManager::getInstance()->isCoroutine()){
  34. return Coroutine::call_user_func($callable,...$params);
  35. }else{
  36. return call_user_func($callable,...$params);
  37. }
  38. }
  39. public static function callUserFuncArray(callable $callable,array $params)
  40. {
  41. if(ServerManager::getInstance()->isCoroutine()){
  42. return Coroutine::call_user_func_array($callable,$params);
  43. }else{
  44. return call_user_func_array($callable,$params);
  45. }
  46. }
  47. }

使用实例

限制函数执行时间

  1. try{
  2. \EasySwoole\Core\Component\Invoker::exec(function (){
  3. sleep(2);
  4. });
  5. }catch (Throwable $throwable){
  6. echo $throwable->getMessage();
  7. }