updateTaskStatus($taskId, 'processing', [ 'start_time' => date('Y-m-d H:i:s'), 'retry_count' => $job->attempts() ]); // 执行成本计算 $result = $this->executeCostCalculation($month, $data['sys_id'] ?? ''); if ($result['success']) { // 任务成功 $job->delete(); $this->updateTaskStatus($taskId, 'success', [ 'end_time' => date('Y-m-d H:i:s'), 'result' => json_encode($result, JSON_UNESCAPED_UNICODE) ]); Log::info('成本计算任务执行成功', ['month' => $month, 'result' => $result]); } else { // 任务失败 if ($job->attempts() >= 3) { $job->delete(); $this->updateTaskStatus($taskId, 'failed', [ 'end_time' => date('Y-m-d H:i:s'), 'error' => $result['message'], 'retry_count' => $job->attempts() ]); Log::error('成本计算任务重试超过3次失败', ['month' => $month, 'error' => $result['message']]); } else { $delay = $this->getRetryDelay($job->attempts()); $job->release($delay); Log::warning('成本计算任务重试', ['month' => $month, 'attempts' => $job->attempts(), 'delay' => $delay]); } } } catch (\Exception $e) { Log::error('成本计算队列任务异常: ' . $e->getMessage()); if ($job->attempts() >= 3) { $job->delete(); $this->updateTaskStatus($taskId ?? 0, 'error', [ 'end_time' => date('Y-m-d H:i:s'), 'error' => $e->getMessage(), 'retry_count' => $job->attempts() ]); } else { $job->release(60); // 延迟60秒重试 } } } /** * 执行成本计算 */ protected function executeCostCalculation(string $month, string $sysId = ''): array { try { // 这里调用您的成本计算服务 $service = new \app\service\UnifiedCostCalculationService(); return $service->calculateAndSaveAll([ 'month' => $month, 'sys_id' => $sysId, ]); } catch (\Exception $e) { return [ 'success' => false, 'message' => '成本计算执行失败: ' . $e->getMessage() ]; } } /** * 更新任务状态 */ protected function updateTaskStatus(int $taskId, string $status, array $data = []): void { if ($taskId <= 0) return; $updateData = array_merge(['status' => $status, 'update_time' => date('Y-m-d H:i:s')], $data); Db::name('queue_tasks') ->where('id', $taskId) ->update($updateData); } /** * 获取重试延迟时间 */ protected function getRetryDelay(int $attempts): int { $delays = [10, 30, 60]; // 10秒, 30秒, 1分钟 return $delays[min($attempts - 1, count($delays) - 1)] ?? 60; } }