SyncTaskCenterCommand.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\MpTaskCenter;
  4. use App\Services\TaskCenterService;
  5. use Illuminate\Console\Command;
  6. class SyncTaskCenterCommand extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'taskCenter:sync';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = '定时同步任务中心状态和结果';
  20. /**
  21. * Execute the console command.
  22. *
  23. * @param TaskCenterService $taskCenterService
  24. * @return int
  25. */
  26. public function handle(TaskCenterService $taskCenterService)
  27. {
  28. dLog('command')->info('开始同步任务中心状态...');
  29. try {
  30. // 提前退出机制:没有排队(pending)或处理中(processing)的任务时直接返回
  31. $pendingCount = MpTaskCenter::whereIn('status', [
  32. MpTaskCenter::STATUS_PENDING,
  33. MpTaskCenter::STATUS_PROCESSING,
  34. ])
  35. ->where('ref_task_id', '>', 0)
  36. ->count('id');
  37. if ($pendingCount <= 0) {
  38. dLog('command')->info('任务中心没有待处理任务,直接返回');
  39. return 0;
  40. }
  41. // 每5秒查询一轮结果,最大持续50秒
  42. $timeStart = time();
  43. $maxDuration = 50;
  44. $checkInterval = 10;
  45. $updated = 0;
  46. while (time() - $timeStart < $maxDuration) {
  47. $updated += $taskCenterService->syncTaskStatus();
  48. // 本轮同步后重新统计,全部完成则提前退出
  49. $pendingCount = MpTaskCenter::whereIn('status', [
  50. MpTaskCenter::STATUS_PENDING,
  51. MpTaskCenter::STATUS_PROCESSING,
  52. ])
  53. ->where('ref_task_id', '>', 0)
  54. ->count('id');
  55. if ($pendingCount <= 0) {
  56. dLog('command')->info('任务中心任务已全部处理完成,提前退出');
  57. break;
  58. }
  59. sleep($checkInterval);
  60. }
  61. dLog('command')->info('任务中心同步完成,更新记录数: ' . $updated);
  62. } catch (\Exception $e) {
  63. dLog('command')->error('任务中心同步失败: ' . $e->getMessage());
  64. logDB('command', 'error', '任务中心同步失败', ['error' => $e->getMessage()]);
  65. return 1;
  66. }
  67. return 0;
  68. }
  69. }