| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- <?php
- namespace App\Console\Commands;
- use App\Models\MpTaskCenter;
- use App\Services\TaskCenterService;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\DB;
- class SyncTaskCenterCommand extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'taskCenter:sync';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = '定时同步任务中心状态和结果';
- /**
- * Execute the console command.
- *
- * @param TaskCenterService $taskCenterService
- * @return int
- */
- public function handle(TaskCenterService $taskCenterService)
- {
- // 将剧本资产生成任务表的超时任务设置为失败
- DB::table('mp_script_generate_tasks')
- ->where('status', 'processing')
- ->where('started_at', '<', date('Y-m-d H:i:s', strtotime('-1 hour')))
- ->update([
- 'status' => 'failed',
- 'error_message' => '任务超时',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- dLog('command')->info('开始同步任务中心状态...');
- try {
- // 提前退出机制:没有排队(pending)或处理中(processing)的任务时直接返回
- $pendingCount = MpTaskCenter::whereIn('status', [
- MpTaskCenter::STATUS_PENDING,
- MpTaskCenter::STATUS_PROCESSING,
- ])
- ->where('ref_task_id', '>', 0)
- ->count('id');
- if ($pendingCount <= 0) {
- dLog('command')->info('任务中心没有待处理任务,直接返回');
- return 0;
- }
- // 每5秒查询一轮结果,最大持续50秒
- $timeStart = time();
- $maxDuration = 50;
- $checkInterval = 10;
- $updated = 0;
- while (time() - $timeStart < $maxDuration) {
- $updated += $taskCenterService->syncTaskStatus();
- // 本轮同步后重新统计,全部完成则提前退出
- $pendingCount = MpTaskCenter::whereIn('status', [
- MpTaskCenter::STATUS_PENDING,
- MpTaskCenter::STATUS_PROCESSING,
- ])
- ->where('ref_task_id', '>', 0)
- ->count('id');
- if ($pendingCount <= 0) {
- dLog('command')->info('任务中心任务已全部处理完成,提前退出');
- break;
- }
- sleep($checkInterval);
- }
- dLog('command')->info('任务中心同步完成,更新记录数: ' . $updated);
- } catch (\Exception $e) {
- dLog('command')->error('任务中心同步失败: ' . $e->getMessage());
- logDB('command', 'error', '任务中心同步失败', ['error' => $e->getMessage()]);
- return 1;
- }
- return 0;
- }
- }
|