多个进程开启定时任务, 执行时间还是同时,可否时间不变, 不同时执行

xiaoming

问题描述

public static function onWorkerStart($worker)
{

        Timer::add(5, function () {
            if(empty(self::$heartbeat_queue)){
                return;
            }
            StoreWs::where("id", 'in', self::$heartbeat_queue)->update(['heartbeat_time' => time()]);
            self::$heartbeat_queue = [];
        });
}
204 3 0
3个回答

xiaoming

可这样子嵌套 ?

  Timer::add($worker->id+1, function () {
            Timer::add(5, function () {
                if(empty(self::$heartbeat_queue)){
                    return;
                }
                StoreWs::where("id", 'in', self::$heartbeat_queue)->update(['heartbeat_time' => time()]);
                self::$heartbeat_queue = [];
            });
        },[],false);
  • rbb 16天前

    这样不用嵌套了吧,Timer::add(5+$worker->id, function () {}

  • xiaoming 15天前

    周期就不是都5秒了

释永战

Timer::add前面加一句sleep($worker->id);

  • xiaoming 15天前

    这样子不太好

  • 释永战 15天前

    是哪里不太好?我就是用的这种方案,用了十几年了目前没有任何问题····

ichynul

估计你是想任务在不同进程不同时执行吧,我做过类似的,把任务按顺序分配到不同的进程。

$threadTotal = $worker->count; //总进程数量 n
$threadId = $worker->id; //当前进程编号 1 ~ (n-1)
$i = -1;
foreach ($taskList as $li) {
     $i += 1;
     if ($i % $threadTotal != $threadId) {
          continue;
     }
     $this->curl($li['url']);
}
  • xiaoming 15天前

    是的周期都是5秒定时 但是不同时刻 执行

  • ichynul 15天前
    $queueIds = [];
    foreach (self::$heartbeat_queue as $i => $q) {
         if ($i % $threadTotal != $threadId) {
              continue;
         }
        $queueIds[]= $q;
        unset(self::$heartbeat_queue[$i]);
    }
    
    StoreWs::where("id", 'in', $queueIds)->update(['heartbeat_time' => time()]);

    同时执行,但不同的进程不会对同一个queueId重复执行。

🔝