定制 denismitr/async-runner 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

denismitr/async-runner

Composer 安装命令:

composer require denismitr/async-runner

包简介

Run PHP tasks asynchronously with the PCNTL extension

README 文档

README

Build Status

Run PHP tasks asynchronously with the PCNTL extension

Installation

composer require denismitr/async-runner

Usage

$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

Example with AsyncTask inheritance

// 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
}

You can check the result of each task by id, to help preserve the order

$wg = WaitGroup::create();

$idA = $wg->add(new TestAsyncTask('foo'))->getId();
$idB = $wg->add(new TestAsyncTask('bar'))->getId();
$idC = $wg->add(new TestAsyncTask('baz'))->getId();

$results = $wg->wait();

$this->assertEquals('foo', $results[$idA]);
$this->assertEquals('bar', $results[$idB]);
$this->assertEquals('baz', $results[$idC]);

You can set max concurrent processes limit

$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

You can set a timeout

$wg = WaitGroup::create()->setTimeout(3);

$timedOut = 0;

foreach (range(1, 5) as $i) {
    $wg->add(function () use ($i) {
        sleep($i);
    })->timeout(function () use (&$timedOut) {
        $timedOut += 1;
    });
}

$wg->wait();

$this->assertEquals(3, $timedOut);

统计信息

  • 总下载量: 16
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-05-18

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固