GluSalaryCalculationJob.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace app\job;
  3. use app\service\GluSalaryCalculationService;
  4. use think\Db;
  5. use think\Log;
  6. /**
  7. * 糊盒工资计算队列任务
  8. */
  9. class GluSalaryCalculationJob
  10. {
  11. /**
  12. * @param \think\queue\Job $job
  13. * @param array $data
  14. */
  15. public function fire($job, $data)
  16. {
  17. $taskId = $data['task_id'] ?? 0;
  18. try {
  19. Log::info('开始执行糊盒工资计算队列任务', $data);
  20. $this->updateTaskStatus($taskId, 'processing', [
  21. 'start_time' => date('Y-m-d H:i:s'),
  22. 'retry_count' => $job->attempts(),
  23. ]);
  24. $service = new GluSalaryCalculationService();
  25. $result = $service->execute($data);
  26. if (!empty($result['success'])) {
  27. $job->delete();
  28. $this->updateTaskStatus($taskId, 'success', [
  29. 'end_time' => date('Y-m-d H:i:s'),
  30. 'result' => json_encode($result, JSON_UNESCAPED_UNICODE),
  31. ]);
  32. Log::info('糊盒工资计算任务执行成功', $result);
  33. return;
  34. }
  35. $message = $result['message'] ?? '糊盒工资计算失败';
  36. $maxRetry = config('queue.queues.salary_calculation.retry') ?? 2;
  37. if ($job->attempts() >= $maxRetry) {
  38. $job->delete();
  39. $this->updateTaskStatus($taskId, 'failed', [
  40. 'end_time' => date('Y-m-d H:i:s'),
  41. 'error' => $message,
  42. 'retry_count' => $job->attempts(),
  43. ]);
  44. Log::error('糊盒工资计算任务失败', ['data' => $data, 'error' => $message]);
  45. return;
  46. }
  47. $job->release($this->getRetryDelay($job->attempts()));
  48. Log::warning('糊盒工资计算任务重试', ['attempts' => $job->attempts(), 'error' => $message]);
  49. } catch (\Exception $e) {
  50. Log::error('糊盒工资计算队列任务异常: ' . $e->getMessage());
  51. $maxRetry = config('queue.queues.salary_calculation.retry') ?? 2;
  52. if ($job->attempts() >= $maxRetry) {
  53. $job->delete();
  54. $this->updateTaskStatus($taskId, 'error', [
  55. 'end_time' => date('Y-m-d H:i:s'),
  56. 'error' => $e->getMessage(),
  57. 'retry_count' => $job->attempts(),
  58. ]);
  59. return;
  60. }
  61. $job->release(60);
  62. }
  63. }
  64. protected function updateTaskStatus($taskId, $status, array $data = [])
  65. {
  66. if (empty($taskId)) {
  67. return;
  68. }
  69. Db::name('queue_tasks')
  70. ->where('id', $taskId)
  71. ->update(array_merge([
  72. 'status' => $status,
  73. 'update_time' => date('Y-m-d H:i:s'),
  74. ], $data));
  75. }
  76. protected function getRetryDelay($attempts)
  77. {
  78. $delays = [10, 30, 60];
  79. return $delays[min($attempts - 1, count($delays) - 1)] ?? 60;
  80. }
  81. }