1. Go to this page and download the library: Download denismitr/async-runner 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/ */
denismitr / async-runner example snippets
$wg = WaitGroup::create();
$counter = 0;
foreach (range(1, 10) as $i) {
$wg->add(function () {
usleep(200); // some action here that takes time
return 5;
})->then(function (int $result) use (&$counter) {
$counter += $result;
});
}
$wg->wait();
$counter; // 50
// Create a class(es) that inherit from AsyncTask
use Denismitr\Async\AsyncTask;
class TestAsyncTask1 extends AsyncTask
{
public function __construct($passSomething)
{
// Some initialization here
}
public function run()
{
usleep(1000); // some action here
return 'some result';
}
}
// Run
$wg = WaitGroup::create();
$wg->add(new TestAsyncTask1($passSomething));
$wg->add(new TestAsyncTask2($passSomething));
$results = $wg->wait();
foreach($results as $result) {
// gives 2 results of 2 async tasks
}
$wg = WaitGroup::create()->setMaxConcurrently(2);
$startTime = microtime(true);
foreach (range(1, 3) as $i) {
$wg->add(function () {
sleep(1);
});
}
$wg->wait(); // Will run only 2 tasks in parallell, then the 3rd one