| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace app\job;
- use app\service\GluSalaryCalculationService;
- use think\Db;
- use think\Log;
- /**
- * 糊盒工资计算队列任务
- */
- class GluSalaryCalculationJob
- {
- /**
- * @param \think\queue\Job $job
- * @param array $data
- */
- public function fire($job, $data)
- {
- $taskId = $data['task_id'] ?? 0;
- try {
- Log::info('开始执行糊盒工资计算队列任务', $data);
- $this->updateTaskStatus($taskId, 'processing', [
- 'start_time' => date('Y-m-d H:i:s'),
- 'retry_count' => $job->attempts(),
- ]);
- $service = new GluSalaryCalculationService();
- $result = $service->execute($data);
- if (!empty($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('糊盒工资计算任务执行成功', $result);
- return;
- }
- $message = $result['message'] ?? '糊盒工资计算失败';
- $maxRetry = config('queue.queues.salary_calculation.retry') ?? 2;
- if ($job->attempts() >= $maxRetry) {
- $job->delete();
- $this->updateTaskStatus($taskId, 'failed', [
- 'end_time' => date('Y-m-d H:i:s'),
- 'error' => $message,
- 'retry_count' => $job->attempts(),
- ]);
- Log::error('糊盒工资计算任务失败', ['data' => $data, 'error' => $message]);
- return;
- }
- $job->release($this->getRetryDelay($job->attempts()));
- Log::warning('糊盒工资计算任务重试', ['attempts' => $job->attempts(), 'error' => $message]);
- } catch (\Exception $e) {
- Log::error('糊盒工资计算队列任务异常: ' . $e->getMessage());
- $maxRetry = config('queue.queues.salary_calculation.retry') ?? 2;
- if ($job->attempts() >= $maxRetry) {
- $job->delete();
- $this->updateTaskStatus($taskId, 'error', [
- 'end_time' => date('Y-m-d H:i:s'),
- 'error' => $e->getMessage(),
- 'retry_count' => $job->attempts(),
- ]);
- return;
- }
- $job->release(60);
- }
- }
- protected function updateTaskStatus($taskId, $status, array $data = [])
- {
- if (empty($taskId)) {
- return;
- }
- Db::name('queue_tasks')
- ->where('id', $taskId)
- ->update(array_merge([
- 'status' => $status,
- 'update_time' => date('Y-m-d H:i:s'),
- ], $data));
- }
- protected function getRetryDelay($attempts)
- {
- $delays = [10, 30, 60];
- return $delays[min($attempts - 1, count($delays) - 1)] ?? 60;
- }
- }
|