Timeouts in PHP
Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in PHP is possible using non-blocking I/O and the stream_select()
function.
Running this program shows the first operation timing out and the second succeeding.
In this PHP implementation:
We define a
longRunningTask()
function that simulates a task taking 2 seconds to complete.The
runWithTimeout()
function takes a callback and a timeout duration as arguments. It usespcntl_fork()
to create a child process that runs the long-running task.In the parent process, we use
stream_select()
to wait for either the result from the child process or for the timeout to occur.If the timeout occurs before the result is received, we terminate the child process and return “timeout”.
If the result is received before the timeout, we return the result.
We run the long-running task twice: once with a 1-second timeout (which results in a timeout) and once with a 3-second timeout (which allows the task to complete).
Note that this implementation requires the pcntl
extension to be enabled in PHP, which is typically available on Unix-like systems but not on Windows. For a more portable solution, you might consider using asynchronous libraries like ReactPHP or Amp.