業(yè)務(wù)需要定時(shí)去PLC獲取數(shù)據(jù),為此我在一個(gè)進(jìn)程內(nèi),定義了多個(gè)定時(shí)器
foreach ($devicePlcs as $devicePlc) {
// 如果不存在,則表示新增,需創(chuàng)建timer數(shù)組
if (!isset($this->timers[$devicePlc->id])) {
$timer_id = Timer::add($this->execute, function() use ($devicePlc) {
$this->executeDeviceTask2($devicePlc); // 執(zhí)行實(shí)際業(yè)務(wù)代碼;
});
$this->timers[$devicePlc->id] = ['timer_id' => $timer_id]; // 往timers數(shù)組設(shè)置該key
}
}
然后這是我的業(yè)務(wù)代碼,在$new和$totalCount之間需要有間隔100ms的延遲,這是PLC本身的機(jī)制所決定的。
但是如果加入了sleep(1)的話,他理論上是n個(gè)sleep(1)同時(shí)阻礙著進(jìn)程的,有啥好的方案?
protected function executeDeviceTask2($devicePlc)
{
// 提取舊值
if (empty($devicePlc->params)) {
// notthing to do
} else {
$old = $devicePlc->params;
}
$connection = BinaryStreamConnection::getBuilder()->setPort(502)->setHost($devicePlc->ip)->setConnectTimeoutSec(2.5)->setWriteTimeoutSec(0.5)->setReadTimeoutSec(1.5)->build();
$new = $this->readHoldingRegisters($connection, $devicePlc, 25, 1, 1);
$totalCount = $this->readHoldingRegisters($connection, $devicePlc, 400, 2, 0); // 累計(jì)計(jì)數(shù)
var_dump($new, $totalCount);
}
百度無果
再來一次 Timer
,相當(dāng)于將 Timer
作為異步隊(duì)列來用,但如果定時(shí)器里的業(yè)務(wù)很慢,會(huì)影響當(dāng)前進(jìn)程處理其它請(qǐng)求。
Timer::add(0.1, function () use ($connection, $devicePlc, $new) {
$totalCount = $this->readHoldingRegisters($connection, $devicePlc, 400, 2, 0);
var_dump($new, $totalCount);
}, [], false);