总感觉是错误的,请大神知道workerman中的timer类的使用

bobshipwood

问题描述

$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']);这个方法可以理解成在一个队列中,把这个任务给清理掉了吗?

200 1 1
1个回答

lunzi

没看到timers数组的作用,要是我写的话就这样

if($worker->id == 0) {
    Timer::add(60, function() {
        $service = app()->make(DeviceModelService::class);
        $devices = $service->getActiveDevices(); // 假设这个方法返回所有需要定时任务的设备
        while($device = array_pop($devices)) {
            Timer::add($device->ror_second, function() use ($device){
                // 执行业务代码
                Device485::dispatch($device->device_id,$device->model_id, $device->address);
            });
        }
    })
}
  • lunzi 25天前

    其他的查询条件写在getActiveDevices里,反正都是要一分钟调用一次

×
🔝