Re: Running a code block with timeout
| From: | Matthew Zand | Date: | Wed, 30 Oct 2019 13:54:08 +0000 |
| Subject: | Re: Running a code block with timeout | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-326935@lists.php.net to get a copy of this message | ||
Hey guys,
How I can un-subscribe from php-general@lists.php.net
Thx,
Matt
On Wed, Oct 30, 2019 at 9:02 AM helices <mike@mdsresource.net> wrote:
> On Wed, Oct 30, 2019 at 7:02 AM Marcos Passos <marcospassos.com@gmail.com>
> wrote:
>
>> Hi everyone,
>>
>> We're looking for a way to run a code block with a timeout.
>>
>> Our use case involves evaluating an expression written in a custom DSL
>> (similar to Symfony Expression Language), and we want to ensure that the
>> execution will not exceed a given time limit.
>>
>> We tried a naive approach using set_time_limit, but there is no way to
>> catch the exception from the block code that timed out. We then considered
>> using PCNTL, but its use is discouraged production environments.
>>
>> Do you guys have any suggestions?
>>
>> - Marcos
>>
>
>
> We use the following successfully:
>
> //
> // GLOBALS
> $CHILD_PID = 0;
> $PID = getmypid();
> $TIMEOUT = $timeout_seconds;
>
> //
> // BEGIN timer here
> //
>
> // If set to (0), no time limit is imposed
> set_time_limit(0);
>
> // Set timer here
> set_timeout();
>
> //
> // Do actual upload HERE:
> //
>
> //
> // END timer here
> //
> clear_timeout($CHILD_PID);
>
> //
> // FUNCTIONS
> //
>
> //
> // Stop timer
> function clear_timeout($CHILD_PID) {
> posix_kill($CHILD_PID, SIGTERM);
> }
>
> //
> // Set timeout timer
> function set_timeout() {
> global $CHILD_PID, $PID, $TIMEOUT;
>
> $CHILD_PID = pcntl_fork();
>
> if($CHILD_PID == 0) {
> sleep($TIMEOUT);
> posix_kill($PID, SIGTERM);
>
> exitHandler(
> ...
> );
> }
> }
>
>
>
> ~ Mike
>
--
Best,
DC Web Makers <https://blockchain.dcwebmakers.com/>
Coding Bootcamps <https://coding-bootcamps.com/>
240-200-6131
301-327-8773