$worker = new Worker();
$worker->count = 4;
$worker->onWorkerStart = function ($worker) {
try {
switch ($worker->id) {
case 0:
$timers = []; // 保存相关485网关的定时器任务
Timer::add(60, function () use (&$timers) { // 每隔1分钟检测一次数据库的值, 查询有没有新建的设备
$service = app()->make(DeviceModelService::class);
$devices = $service->getActiveDevices(); // 假设这个方法返回所有需要定时任务的设备
foreach ($devices as $device) {
if (isset($timers[$device->id]) && $timers[$device->id]['interval'] != $device->ror_second) {
Timer::del($timers[$device->id]['timer_id']);
unset($timers[$device->id]);
}
if (!isset($timers[$device->id])) {
$timer_id = Timer::add($device->ror_second, function() use ($device){
// 执行业务代码
Device485::dispatch($device->device_id,$device->model_id, $device->address);
});
$timers[$device->id] = [
'timer_id' => $timer_id,
'interval' => $device->ror_second
];
}
}
});
break;
上面的代码首选判断间隔时间是否和数据库设定的值相同,如果不同,则进行删除定时任务,然后再次添加定时任务。
想知道Timer::del($timers[$device->id]['timer_id']);这个方法可以理解成在一个队列中,把这个任务给清理掉了吗?
没看到timers数组的作用,要是我写的话就这样
其他的查询条件写在getActiveDevices里,反正都是要一分钟调用一次