# Asynchronous Signal Handling

> Section in “New and Extended Functionality › Language Features” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/language-features/asynchronous-signal-handling/>

The executor of PHP’s runtime was extended with safe time-out and interrupt handling capabilities. This allows for callbacks to be called on each loop iteration, userland function entry, or internal function exit and does not require the clumsy, old-fashioned ticks feature.

Asynchronous signal handling is turned off by default. To enable it, simply call `pcntl_async_signals(1)`. You can then use signal handling functions such as `pcntl_signal()` and `pcntl_alarm()`, for instance, as usual:

``` php
pcntl_signal(
    SIGALRM,
    function () {
        throw new Exception;
    },
    true
);

pcntl_async_signals(true);
pcntl_alarm(1);

sleep(2);
```

In the example shown above, we register an anonymous function as a callback for the `SIGALRM` event using the `pcntl_signal()` function. We then use the `pcntl_alarm()` function to instruct PHP to trigger an `SIGALRM` event after one second. We then `sleep()` for two seconds but are interrupted by an exception after one second because of the alarm:

    Fatal error: Uncaught Exception in example.php:5
    Stack trace:
    #0 example.php(13): {closure}(14, Array)
    #1 {main}
      thrown in example.php on line 5

Please note that such an alarm cannot be triggered while the PHP runtime is performing an I/O operation or is executing library code that is used by an extension. An alarm such as the one shown in the previous example will then be triggered as soon as the PHP runtime finished an I/O operation, for instance.

---

Previous: [is_countable()](https://php7explained.com/new-and-extended-functionality/language-features/is_countable/index.html.md) | Next: [spl_object_id()](https://php7explained.com/new-and-extended-functionality/language-features/spl_object_id/index.html.md)
