func_timeout.php 779 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. declare(ticks = 1);
  3. Swoole\Async::set([
  4. 'enable_signalfd' => false,
  5. ]);
  6. class FunctionTimeoutException extends RuntimeException
  7. {
  8. }
  9. function test()
  10. {
  11. sleep(1);
  12. }
  13. $serv = new Swoole\Http\Server("127.0.0.1", 9502);
  14. $serv->set(['worker_num' => 1]);
  15. $serv->on('WorkerStart', function($serv, $workerId) {
  16. pcntl_signal(SIGALRM, function () {
  17. Swoole\Process::alarm(-1);
  18. throw new FunctionTimeoutException;
  19. });
  20. });
  21. $serv->on('Request', function($request, $response) {
  22. try
  23. {
  24. Swoole\Process::alarm(100 * 1000);
  25. test();
  26. Swoole\Process::alarm(-1);
  27. $response->end("<h1>Finish</h1>");
  28. }
  29. catch(FunctionTimeoutException $e)
  30. {
  31. $response->end("<h1>Timeout</h1>");
  32. }
  33. });
  34. $serv->start();