Set timeout for PHP function execution _ PHP Tutorial

Source: Internet
Author: User
Set timeout for PHP function execution. How can we prevent a function from being executed for too long? In PHP, you can use pcntl clock signals + exceptions. The code is as follows: declare (ticks1); functiona () {sleep (10); how does echoafinishi prevent a function from taking too long to execute? In PHP, you can use pcntl clock signals + exceptions.

The code is as follows:

declare(ticks = 1);    function a(){    sleep(10);    echo "a finishi\n";}function b(){    echo "Stop\n";}function c(){    usleep(100000);}function sig(){    throw new Exception;}try{    pcntl_alarm(1);    pcntl_signal(SIGALRM, "sig");    a();    pcntl_alarm(0);}catch(Exception $e){    echo "timeout\n";}b();a();b();

  

The principle is to set a clock signal before the function is executed. if the execution of the function exceeds the specified time, the signal is triggered, and the signal processing function throws an exception and is captured by the outer code.

In this way, the execution of the original function is jumped out, and the following code is executed. If the function does not trigger the clock signal within the specified time period, and the clock signal is cleared after the function ends, no exception is thrown.

Why? In PHP, you can use pcntl clock signals + exceptions. The code is as follows: declare (ticks = 1); function a () {sleep (10); echo "a finishi \...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.