SyncTaskCenterCommand.php 2.9 KB

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