| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <?php
- namespace app\job;
- use think\Db;
- use think\Log;
- /**
- * 成本计算队列任务
- */
- class UnifiedCostCalculationJob
- {
- /**
- * 任务处理方法
- * @param \think\Job $job 任务对象
- * @param array $data 任务数据
- */
- public function fire($job, $data)
- {
- try {
- Log::info('开始执行成本计算队列任务', $data);
- // 获取任务ID
- $taskId = $data['task_id'] ?? 0;
- $month = $data['month'];
- // 更新任务状态为执行中
- $this->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;
- }
- }
|