workerman/http-client 增加任務處理進度及全部處理結束后回調方法
<?php
use \Workerman\Worker;
class waitGroup {
public bool $isWorkering = false;
public int $workerCounts = 0;
public int $workerOkCounts = 0;
public $func = null;
private int $startTime = 0;
public function __construct() {
$this->isWorkering = true;
}
/**
* 增加任務計數
* @param int $counts 任務數量
*/
public function Add(int $counts = 1) {
if (!$this->startTime) {
$this->startTime = microtime(true);
}
$this->workerCounts += $counts;
}
/**
* 子任務完成
* @param object $func 回調函數
* @field int $workerOkCounts 已完成的任務數
* @field int workerCounts 任務總數
*/
public function Done($func = null) {
$this->workerOkCounts += 1;
if ($func) {
call_user_func($func, $this->workerOkCounts, $this->workerCounts);
}
if ($this->isWorkering && $this->func && $this->workerOkCounts >= $this->workerCounts) {
$this->complete();
}
}
/**
* 任務執(zhí)行完成后回調
* @param object $func 回調函數
*/
public function Wait($func = null) {
$this->func = $func;
}
/**
* complete 完成操作后回調
* @field workerCounts int 任務總數
* @field workerTimer int 任務執(zhí)行總時間,單位:秒
*/
private function complete() {
call_user_func($this->func, $this->workerCounts, (microtime(true) - $this->startTime));
return true;
}
}
$worker = new Worker();
$worker->count = 1;
$waitGroup = new stdClass;
$worker->onWorkerStart = function () {
$options = [
'max_conn_per_addr' => 30, // 每個地址最多維持多少并發(fā)連接
'keepalive_timeout' => 15, // 連接多長時間不通訊就關閉
'connect_timeout' => 30, // 連接超時時間
'timeout' => 30, // 等待響應的超時時間
];
$http = new Workerman\Http\Client($options);
$urlArr = [];
for ($i = 1; $i <= 100; $i += 1) {
$urlArr[] = 'http://xxxxx.com/test?i=' . $i;
}
$waitGroup = new waitGroup();
$waitGroup->Add(count($urlArr));
$waitGroup->Wait(function ($workerCounts, $workerTimer) {
echo "任務已完成:" ,$workerCounts , ",耗時:", sprintf("%0.3f", $workerTimer) , "秒\n";
});
foreach ($urlArr as $url) {
$http->get($url, function ($response) use ($waitGroup) {
var_dump(['code' => $response->getStatusCode(), 'body' => $response->getBody()->__toString()]);
$waitGroup->Done(function ($workerOkCounts, $workerCounts) {
echo "任務進度:[ok] " , $workerOkCounts , "/" , $workerCounts,"\n";
});
}, function ($exception) use ($waitGroup) {
$waitGroup->Done(function ($workerOkCounts, $workerCounts) {
echo "任務進度:[error] " , $workerOkCounts , "/" , $workerCounts,"\n";
});
echo $exception;
});
}
};
個評論
年代過于久遠,無法發(fā)表評論