| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251 |
- <?php
- namespace App\Module\Task\Commands;
- use App\Module\Task\Enums\TASK_STATUS;
- use App\Module\Task\Models\Task;
- use App\Module\Task\Models\TaskUserTask;
- use Illuminate\Console\Command;
- use Illuminate\Support\Carbon;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- /**
- * 清理过期任务命令
- *
- * 用于清理已过期的任务,包括:
- * 1. 已过期的任务(任务的结束时间已过)
- * 2. 已超时的任务(任务的时间限制已过)
- */
- class CleanExpiredTasksCommand extends Command
- {
- /**
- * 命令名称
- *
- * @var string
- */
- protected $signature = 'task:clean-expired
- {--user-id= : 指定用户ID进行清理}
- {--task-id= : 指定任务ID进行清理}
- {--days=30 : 清理多少天前的过期任务}
- {--batch-size=100 : 每批处理的数量}
- {--dry-run : 仅检查不执行实际操作}';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = '清理过期任务';
- /**
- * 执行命令
- *
- * @return int
- */
- public function handle()
- {
- $this->info('开始清理过期任务...');
-
- // 获取命令选项
- $userId = $this->option('user-id');
- $taskId = $this->option('task-id');
- $days = $this->option('days');
- $batchSize = $this->option('batch-size');
- $dryRun = $this->option('dry-run');
-
- // 清理已过期的任务(任务的结束时间已过)
- $this->cleanExpiredByEndTime($userId, $taskId, $days, $batchSize, $dryRun);
-
- // 清理已超时的任务(任务的时间限制已过)
- $this->cleanExpiredByTimeLimit($userId, $taskId, $days, $batchSize, $dryRun);
-
- $this->info('过期任务清理完成');
-
- return 0;
- }
-
- /**
- * 清理已过期的任务(任务的结束时间已过)
- *
- * @param int|null $userId 用户ID
- * @param int|null $taskId 任务ID
- * @param int $days 天数
- * @param int $batchSize 批处理大小
- * @param bool $dryRun 是否仅检查
- * @return void
- */
- protected function cleanExpiredByEndTime(?int $userId, ?int $taskId, int $days, int $batchSize, bool $dryRun): void
- {
- $this->info('清理已过期的任务(任务的结束时间已过)...');
-
- // 获取已过期的任务
- $expiredTasks = Task::where('end_time', '<', Carbon::now()->subDays($days))
- ->where('is_active', true)
- ->get();
-
- if ($expiredTasks->isEmpty()) {
- $this->info('没有找到已过期的任务');
- return;
- }
-
- $this->info("找到 {$expiredTasks->count()} 个已过期的任务");
-
- if ($dryRun) {
- $this->warn('仅检查模式,不执行实际操作');
- return;
- }
-
- // 创建进度条
- $bar = $this->output->createProgressBar($expiredTasks->count());
- $bar->start();
-
- // 处理每个过期任务
- foreach ($expiredTasks as $task) {
- try {
- // 构建查询
- $query = TaskUserTask::query()
- ->where('task_id', $task->id)
- ->whereIn('status', [TASK_STATUS::NOT_ACCEPTED->value, TASK_STATUS::IN_PROGRESS->value]);
-
- // 应用过滤条件
- if ($userId) {
- $query->where('user_id', $userId);
- }
-
- // 分批处理
- $query->chunk($batchSize, function ($userTasks) use ($task) {
- foreach ($userTasks as $userTask) {
- DB::beginTransaction();
- try {
- // 记录日志
- Log::info('清理过期任务', [
- 'user_id' => $userTask->user_id,
- 'task_id' => $userTask->task_id,
- 'reason' => '任务结束时间已过',
- 'end_time' => $task->end_time,
- ]);
-
- // 删除用户任务
- $userTask->delete();
-
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::error('清理过期任务失败', [
- 'user_id' => $userTask->user_id,
- 'task_id' => $userTask->task_id,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- });
-
- // 更新任务状态
- $task->is_active = false;
- $task->save();
- } catch (\Exception $e) {
- $this->error("处理任务异常: 任务ID={$task->id}, 错误: {$e->getMessage()}");
- }
-
- $bar->advance();
- }
-
- $bar->finish();
- $this->newLine(2);
- }
-
- /**
- * 清理已超时的任务(任务的时间限制已过)
- *
- * @param int|null $userId 用户ID
- * @param int|null $taskId 任务ID
- * @param int $days 天数
- * @param int $batchSize 批处理大小
- * @param bool $dryRun 是否仅检查
- * @return void
- */
- protected function cleanExpiredByTimeLimit(?int $userId, ?int $taskId, int $days, int $batchSize, bool $dryRun): void
- {
- $this->info('清理已超时的任务(任务的时间限制已过)...');
-
- // 构建查询
- $query = TaskUserTask::query()
- ->where('status', TASK_STATUS::IN_PROGRESS->value)
- ->where('accepted_at', '<', Carbon::now()->subDays($days))
- ->whereHas('task', function ($query) {
- $query->whereNotNull('time_limit');
- });
-
- // 应用过滤条件
- if ($userId) {
- $query->where('user_id', $userId);
- }
-
- if ($taskId) {
- $query->where('task_id', $taskId);
- }
-
- // 获取符合条件的任务数量
- $totalTasks = $query->count();
-
- if ($totalTasks === 0) {
- $this->info('没有找到已超时的任务');
- return;
- }
-
- $this->info("找到 {$totalTasks} 个已超时的任务");
-
- if ($dryRun) {
- $this->warn('仅检查模式,不执行实际操作');
- return;
- }
-
- // 创建进度条
- $bar = $this->output->createProgressBar($totalTasks);
- $bar->start();
-
- // 分批处理
- $query->with('task')->chunk($batchSize, function ($userTasks) use ($bar) {
- foreach ($userTasks as $userTask) {
- DB::beginTransaction();
- try {
- // 计算任务是否超时
- $acceptedAt = $userTask->accepted_at;
- $timeLimit = $userTask->task->time_limit;
- $expireAt = $acceptedAt->addSeconds($timeLimit);
-
- if (Carbon::now()->greaterThan($expireAt)) {
- // 记录日志
- Log::info('清理超时任务', [
- 'user_id' => $userTask->user_id,
- 'task_id' => $userTask->task_id,
- 'reason' => '任务时间限制已过',
- 'accepted_at' => $acceptedAt,
- 'time_limit' => $timeLimit,
- 'expire_at' => $expireAt,
- ]);
-
- // 删除用户任务
- $userTask->delete();
- }
-
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::error('清理超时任务失败', [
- 'user_id' => $userTask->user_id,
- 'task_id' => $userTask->task_id,
- 'error' => $e->getMessage(),
- ]);
- $this->error("处理任务异常: 用户ID={$userTask->user_id}, 任务ID={$userTask->task_id}, 错误: {$e->getMessage()}");
- }
-
- $bar->advance();
- }
- });
-
- $bar->finish();
- $this->newLine(2);
- }
- }
|