setName('switch:friends') ->setDescription('切换好友命令'); } protected function execute(Input $input, Output $output) { $cacheKey = 'allotWechatFriend'; $now = time(); $maxRetry = 5; $retry = 0; $switchedIds = []; do { $friends = Cache::get($cacheKey, []); $original = $friends; $toSwitch = []; foreach ($friends as $friend) { if (isset($friend['time']) && $friend['time'] < $now) { $toSwitch[] = $friend; } } if (empty($toSwitch)) { $output->writeln('没有需要切换的好友'); return; } $automaticAssign = new AutomaticAssign(); foreach ($toSwitch as $friend) { $automaticAssign->allotWechatFriend([ 'wechatFriendId' => $friend['friendId'], 'toAccountId' => $friend['accountId'], ], true); $output->writeln('切换好友:' . $friend['friendId'] . ' 到账号:' . $friend['accountId']); $switchedIds[] = $friend['friendId']; } // 过滤掉已切换的,保留未切换和新进来的 $newFriends = Cache::get($cacheKey, []); $updated = []; foreach ($newFriends as $friend) { if (!in_array($friend['friendId'], $switchedIds)) { $updated[] = $friend; } } // 按time升序排序 usort($updated, function($a, $b) { return ($a['time'] ?? 0) <=> ($b['time'] ?? 0); }); $success = Cache::set($cacheKey, $updated); $retry++; } while (!$success && $retry < $maxRetry); $output->writeln('切换完成,缓存已更新并排序'); } }