1. Go to this page and download the library: Download spatie/async library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
spatie / async example snippets
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();
$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.
})
;
$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`
});
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();
Pool::create()
->withBinary('/path/to/php');
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());
class InvokableClass
{
// ...
public function __invoke()
{
// ...
}
}
$pool->add(new InvokableClass(/* ... */));
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)
;
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.