PHPackages                             slothlabdotcom/async - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. slothlabdotcom/async

ActiveLibrary[Queues &amp; Workers](/categories/queues)

slothlabdotcom/async
====================

Asynchronous and parallel PHP with the PCNTL extension

1.7.1(11mo ago)062MITPHPPHP ^8.3

Since Jun 1Pushed 11mo agoCompare

[ Source](https://github.com/SlothLabdotCom/async)[ Packagist](https://packagist.org/packages/slothlabdotcom/async)[ Docs](https://github.com/SlothLabdotCom/async)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/slothlabdotcom-async/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (2)Used By (0)

 [   ![Logo for async](https://camo.githubusercontent.com/f3bbd130a6a017c8615b9e6ec77e238ca3a78d140c2a37618ae04b359bd4c990/68747470733a2f2f7370617469652e62652f7061636b616765732f6865616465722f6173796e632f68746d6c2f6c696768742e77656270)  ](https://spatie.be/open-source?utm_source=github&utm_medium=banner&utm_campaign=async)Asynchronous and parallel PHP
=============================

[](#asynchronous-and-parallel-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d5d3cf7f9b1f9c5765a2d3fac930cc41522be479320422cedaadf4578cb705a4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6173796e632e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/async)[![Tests Status](https://camo.githubusercontent.com/96cf8727e4eb5830fe6c5f1bfe860744bcf8fde4a31efa3ab6f7495d23f612ba/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f6173796e632f72756e2d74657374732e796d6c)](https://camo.githubusercontent.com/96cf8727e4eb5830fe6c5f1bfe860744bcf8fde4a31efa3ab6f7495d23f612ba/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f6173796e632f72756e2d74657374732e796d6c)[![Quality Score](https://camo.githubusercontent.com/b88782b65303e4cebf7119a1890b895ced36e45fa63e5f61aaee5b7fa4fab30e/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f6173796e632e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/async)[![Total Downloads](https://camo.githubusercontent.com/82927eaa459f1b7f811dc7a070611a5996916302a2460362113d33494f594e3c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6173796e632e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/async)

This library provides a small and easy wrapper around PHP's PCNTL extension. It allows running of different processes in parallel, with an easy-to-use API.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/c4ea6e1dd1fee42ed51f54dc01afdc17c53482591bd8769fb7d0292a61c0fb36/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6173796e632e6a70673f743d31)](https://spatie.be/github-ad-click/async)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require slothlabdotcom/async
```

Usage
-----

[](#usage)

```
use Spatie\Async\Pool;

$pool = Pool::create();

foreach ($things as $thing) {
    $pool->add(function () use ($thing) {
        // Do a thing
    })->then(function ($output) {
        // Handle success
    })->catch(function (Throwable $exception) {
        // Handle exception
    });
}

$pool->wait();
```

### Event listeners

[](#event-listeners)

When creating asynchronous processes, you'll get an instance of `ParallelProcess` returned. You can add the following event hooks on a process.

```
$pool
    ->add(function () {
        // ...
    })
    ->then(function ($output) {
        // On success, `$output` is returned by the process or callable you passed to the queue.
    })
    ->catch(function ($exception) {
        // When an exception is thrown from within a process, it's caught and passed here.
    })
    ->timeout(function () {
        // A process took too long to finish.
    })
;
```

### Functional API

[](#functional-api)

Instead of using methods on the `$pool` object, you may also use the `async` and `await` helper functions.

```
use Spatie\Async\Pool;

$pool = Pool::create();

foreach (range(1, 5) as $i) {
    $pool[] = async(function () {
        usleep(random_int(10, 1000));

        return 2;
    })->then(function (int $output) {
        $this->counter += $output;
    });
}

await($pool);
```

### Error handling

[](#error-handling)

If an `Exception` or `Error` is thrown from within a child process, it can be caught per process by specifying a callback in the `->catch()` method.

```
$pool
    ->add(function () {
        // ...
    })
    ->catch(function ($exception) {
        // Handle the thrown exception for this child process.
    })
;
```

If there's no error handler added, the error will be thrown in the parent process when calling `await()` or `$pool->wait()`.

If the child process would unexpectedly stop without throwing an `Throwable`, the output written to `stderr` will be wrapped and thrown as `Spatie\Async\ParallelError` in the parent process.

### Catching exceptions by type

[](#catching-exceptions-by-type)

By type hinting the `catch` functions, you can provide multiple error handlers, each for individual types of errors.

```
$pool
    ->add(function () {
        throw new MyException('test');
    })
    ->catch(function (MyException $e) {
        // Handle `MyException`
    })
    ->catch(function (OtherException $e) {
        // Handle `OtherException`
    });
```

Note that as soon as an exception is handled, it won't trigger any other handlers

```
$pool
    ->add(function () {
        throw new MyException('test');
    })
    ->catch(function (MyException $e) {
        // This one is triggerd when `MyException` is thrown
    })
    ->catch(function (Exception $e) {
        // This one is not triggerd, even though `MyException` extends `Exception`
    });
```

### Stopping a pool

[](#stopping-a-pool)

If you need to stop a pool early, because the task it was performing has been completed by one of the child processes, you can use the `$pool->stop()` method. This will prevent the pool from starting any additional processes.

```
use Spatie\Async\Pool;

$pool = Pool::create();

// Generate 10k processes generating random numbers
for($i = 0; $i < 10000; $i++) {
    $pool->add(function() use ($i) {
        return rand(0, 100);
    })->then(function($output) use ($pool) {
        // If one of them randomly picks 100, end the pool early.
        if ($output === 100) {
            $pool->stop();
        }
    });
}

$pool->wait();
```

Note that a pool will be rendered useless after being stopped, and a new pool should be created if needed.

### Using another PHP binary

[](#using-another-php-binary)

By default the pool will use `php` to execute its child processes. You can configure another binary like so:

```
Pool::create()
    ->withBinary('/path/to/php');
```

### Working with tasks

[](#working-with-tasks)

Besides using closures, you can also work with a `Task`. A `Task` is useful in situations where you need more setup work in the child process. Because a child process is always bootstrapped from nothing, chances are you'll want to initialise eg. the dependency container before executing the task. The `Task` class makes this easier to do.

```
use Spatie\Async\Task;

class MyTask extends Task
{
    public function configure()
    {
        // Setup eg. dependency container, load config,...
    }

    public function run()
    {
        // Do the real work here.
    }
}

// Add the task to the pool
$pool->add(new MyTask());
```

#### Simple tasks

[](#simple-tasks)

If you want to encapsulate the logic of your task, but don't want to create a full blown `Task` object, you may also pass an invokable object to the `Pool`.

```
class InvokableClass
{
    // ...

    public function __invoke()
    {
        // ...
    }
}

$pool->add(new InvokableClass(/* ... */));
```

### Pool configuration

[](#pool-configuration)

You're free to create as many pools as you want, each pool has its own queue of processes it will handle.

A pool is configurable by the developer:

```
use Spatie\Async\Pool;

$pool = Pool::create()

// The maximum amount of processes which can run simultaneously.
    ->concurrency(20)

// The maximum amount of time a process may take to finish in seconds
// (decimal places are supported for more granular timeouts).
    ->timeout(15)

// Configure which autoloader sub processes should use.
    ->autoload(__DIR__ . '/../../vendor/autoload.php')

// Configure how long the loop should sleep before re-checking the process statuses in microseconds.
    ->sleepTime(50000)
;
```

### Synchronous fallback

[](#synchronous-fallback)

If the required extensions (`pcntl` and `posix`) are not installed in your current PHP runtime, the `Pool` will automatically fallback to synchronous execution of tasks.

The `Pool` class has a static method `isSupported` you can call to check whether your platform is able to run asynchronous processes.

If you're using a `Task` to run processes, only the `run` method of those tasks will be called when running in synchronous mode.

Behind the curtains
-------------------

[](#behind-the-curtains)

When using this package, you're probably wondering what's happening underneath the surface.

We're using the `symfony/process` component to create and manage child processes in PHP. By creating child processes on the fly, we're able to execute PHP scripts in parallel. This parallelism can improve performance significantly when dealing with multiple synchronous tasks, which don't really need to wait for each other. By giving these tasks a separate process to run on, the underlying operating system can take care of running them in parallel.

There's a caveat when dynamically spawning processes: you need to make sure that there won't be too many processes at once, or the application might crash. The `Pool` class provided by this package takes care of handling as many processes as you want by scheduling and running them when it's possible.

That's the part that `async()` or `$pool->add()` does. Now let's look at what `await()` or `$pool->wait()` does.

When multiple processes are spawned, each can have a separate time to completion. One process might eg. have to wait for a HTTP call, while the other has to process large amounts of data. Sometimes you also have points in your code which have to wait until the result of a process is returned.

This is why we have to wait at a certain point in time: for all processes on a pool to finish, so we can be sure it's safe to continue without accidentally killing the child processes which aren't done yet.

Waiting for all processes is done by using a `while` loop, which will wait until all processes are finished. Determining when a process is finished is done by using a listener on the `SIGCHLD` signal. This signal is emitted when a child process is finished by the OS kernel. As of PHP 7.1, there's much better support for listening and handling signals, making this approach more performant than eg. using process forks or sockets for communication. You can read more about it [here](https://wiki.php.net/rfc/async_signals).

When a process is finished, its success event is triggered, which you can hook into with the `->then()` function. Likewise, when a process fails or times out, the loop will update that process' status and move on. When all processes are finished, the while loop will see that there's nothing more to wait for, and stop. This is the moment your parent process can continue to execute.

### Comparison to other libraries

[](#comparison-to-other-libraries)

We've written a blog post containing more information about use cases for this package, as well as making comparisons to other asynchronous PHP libraries like ReactPHP and Amp: .

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

### Security

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Brent Roose](https://github.com/brendt)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance51

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 54.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

342d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0c06ac843dc570aaf789602e0be95b1c0d89ee34a9f795e868001e5e41f30582?d=identicon)[BahaStriker](/maintainers/BahaStriker)

---

Top Contributors

[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (172 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (42 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (12 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (10 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (9 commits)")[![oniice](https://avatars.githubusercontent.com/u/2676321?v=4)](https://github.com/oniice "oniice (6 commits)")[![michielkempen](https://avatars.githubusercontent.com/u/14795113?v=4)](https://github.com/michielkempen "michielkempen (6 commits)")[![matthi4s](https://avatars.githubusercontent.com/u/8943286?v=4)](https://github.com/matthi4s "matthi4s (6 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (6 commits)")[![Jord-JD](https://avatars.githubusercontent.com/u/650645?v=4)](https://github.com/Jord-JD "Jord-JD (5 commits)")[![MarcHagen](https://avatars.githubusercontent.com/u/980978?v=4)](https://github.com/MarcHagen "MarcHagen (5 commits)")[![joaorobertopb](https://avatars.githubusercontent.com/u/6556083?v=4)](https://github.com/joaorobertopb "joaorobertopb (4 commits)")[![vuongxuongminh](https://avatars.githubusercontent.com/u/38932626?v=4)](https://github.com/vuongxuongminh "vuongxuongminh (4 commits)")[![Stevemoretz](https://avatars.githubusercontent.com/u/27680142?v=4)](https://github.com/Stevemoretz "Stevemoretz (4 commits)")[![BahaStriker](https://avatars.githubusercontent.com/u/9751325?v=4)](https://github.com/BahaStriker "BahaStriker (3 commits)")[![gazugafan](https://avatars.githubusercontent.com/u/854538?v=4)](https://github.com/gazugafan "gazugafan (2 commits)")[![iasjennen](https://avatars.githubusercontent.com/u/12272672?v=4)](https://github.com/iasjennen "iasjennen (2 commits)")[![jonasraoni](https://avatars.githubusercontent.com/u/361921?v=4)](https://github.com/jonasraoni "jonasraoni (2 commits)")[![jimirobaer](https://avatars.githubusercontent.com/u/8984769?v=4)](https://github.com/jimirobaer "jimirobaer (2 commits)")[![vdbelt](https://avatars.githubusercontent.com/u/11087503?v=4)](https://github.com/vdbelt "vdbelt (2 commits)")

---

Tags

asyncspatie

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/slothlabdotcom-async/health.svg)

```
[![Health](https://phpackages.com/badges/slothlabdotcom-async/health.svg)](https://phpackages.com/packages/slothlabdotcom-async)
```

###  Alternatives

[spatie/async

Asynchronous and parallel PHP with the PCNTL extension

2.8k4.5M37](/packages/spatie-async)[illuminate/queue

The Illuminate Queue package.

20331.4M1.2k](/packages/illuminate-queue)[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[jolicode/castor

A lightweight and modern task runner. Automate everything. In PHP.

53541.0k3](/packages/jolicode-castor)[orisai/scheduler

Cron job scheduler - with locks, parallelism and more

4037.1k4](/packages/orisai-scheduler)[ufo-tech/json-rpc-bundle

The bundle for easy using json-rpc api on your project

224.6k3](/packages/ufo-tech-json-rpc-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
