| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace App\Console\Commands;
- use App\Models\MpTaskCenter;
- use App\Services\TaskCenterService;
- use Illuminate\Console\Command;
- 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)
- {
- 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;
- }
- }
|