CleanJobRunsCommand.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. namespace App\Module\System\Commands;
  3. use App\Module\System\Models\JobRun;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Carbon;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. /**
  9. * 清理job_runs表命令
  10. *
  11. * 用于清理过期的队列运行记录,保持数据库性能
  12. * 默认保留5天内的记录,删除更早的记录
  13. */
  14. class CleanJobRunsCommand extends Command
  15. {
  16. /**
  17. * 命令名称
  18. *
  19. * @var string
  20. */
  21. protected $signature = 'system:clean-job-runs
  22. {--days=5 : 保留多少天的记录,默认5天}
  23. {--batch-size=1000 : 每批处理的数量,默认1000}
  24. {--dry-run : 仅检查不执行实际删除操作}
  25. {--force : 强制执行,跳过确认}';
  26. /**
  27. * 命令描述
  28. *
  29. * @var string
  30. */
  31. protected $description = '清理job_runs表中的过期记录,保留指定天数内的数据';
  32. /**
  33. * 执行命令
  34. *
  35. * @return int
  36. */
  37. public function handle()
  38. {
  39. $this->info('开始清理job_runs表过期记录...');
  40. // 获取命令选项
  41. $days = (int) $this->option('days');
  42. $batchSize = (int) $this->option('batch-size');
  43. $dryRun = $this->option('dry-run');
  44. $force = $this->option('force');
  45. // 验证参数
  46. if ($days < 1) {
  47. $this->error('保留天数必须大于0');
  48. return 1;
  49. }
  50. if ($batchSize < 100 || $batchSize > 10000) {
  51. $this->error('批处理大小必须在100-10000之间');
  52. return 1;
  53. }
  54. // 计算截止时间(保留指定天数内的记录)
  55. $cutoffTime = Carbon::now()->subDays($days)->timestamp;
  56. $cutoffDate = Carbon::createFromTimestamp($cutoffTime)->format('Y-m-d H:i:s');
  57. $this->info("保留天数: {$days}天");
  58. $this->info("截止时间: {$cutoffDate}");
  59. $this->info("批处理大小: {$batchSize}");
  60. // 统计需要清理的记录数
  61. $totalCount = JobRun::where('created_at', '<', $cutoffTime)->count();
  62. if ($totalCount === 0) {
  63. $this->info('没有需要清理的记录');
  64. return 0;
  65. }
  66. $this->info("发现 {$totalCount} 条需要清理的记录");
  67. if ($dryRun) {
  68. $this->warn('预演模式:不会执行实际删除操作');
  69. $this->showCleanupPreview($cutoffTime);
  70. return 0;
  71. }
  72. // 确认操作
  73. if (!$force && !$this->confirm("确定要删除 {$totalCount} 条记录吗?")) {
  74. $this->info('操作已取消');
  75. return 0;
  76. }
  77. // 执行清理
  78. $deletedCount = $this->performCleanup($cutoffTime, $batchSize);
  79. $this->info("清理完成,共删除 {$deletedCount} 条记录");
  80. // 记录操作日志
  81. Log::info('job_runs表清理完成', [
  82. 'command' => 'system:clean-job-runs',
  83. 'days' => $days,
  84. 'cutoff_time' => $cutoffDate,
  85. 'deleted_count' => $deletedCount,
  86. 'batch_size' => $batchSize,
  87. ]);
  88. return 0;
  89. }
  90. /**
  91. * 显示清理预览信息
  92. *
  93. * @param int $cutoffTime
  94. * @return void
  95. */
  96. protected function showCleanupPreview(int $cutoffTime): void
  97. {
  98. $this->info('清理预览:');
  99. // 按状态统计
  100. $statusStats = JobRun::where('created_at', '<', $cutoffTime)
  101. ->select('status', DB::raw('count(*) as count'))
  102. ->groupBy('status')
  103. ->get();
  104. $this->table(['状态', '记录数'], $statusStats->map(function ($item) {
  105. return [$item->status ?: '未知', $item->count];
  106. })->toArray());
  107. // 按队列统计
  108. $queueStats = JobRun::where('created_at', '<', $cutoffTime)
  109. ->select('queue', DB::raw('count(*) as count'))
  110. ->groupBy('queue')
  111. ->orderBy('count', 'desc')
  112. ->limit(10)
  113. ->get();
  114. $this->info('按队列统计(前10):');
  115. $this->table(['队列名称', '记录数'], $queueStats->map(function ($item) {
  116. return [$item->queue ?: 'default', $item->count];
  117. })->toArray());
  118. // 时间范围统计
  119. $oldestRecord = JobRun::where('created_at', '<', $cutoffTime)
  120. ->orderBy('created_at', 'asc')
  121. ->first();
  122. if ($oldestRecord) {
  123. $oldestDate = Carbon::createFromTimestamp($oldestRecord->created_at)->format('Y-m-d H:i:s');
  124. $this->info("最早记录时间: {$oldestDate}");
  125. }
  126. }
  127. /**
  128. * 执行清理操作
  129. *
  130. * @param int $cutoffTime
  131. * @param int $batchSize
  132. * @return int 删除的记录数
  133. */
  134. protected function performCleanup(int $cutoffTime, int $batchSize): int
  135. {
  136. $totalDeleted = 0;
  137. $progressBar = $this->output->createProgressBar();
  138. $progressBar->setFormat('清理进度: %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
  139. do {
  140. DB::beginTransaction();
  141. try {
  142. // 分批删除记录
  143. $deleted = JobRun::where('created_at', '<', $cutoffTime)
  144. ->limit($batchSize)
  145. ->delete();
  146. $totalDeleted += $deleted;
  147. $progressBar->advance($deleted);
  148. DB::commit();
  149. // 避免长时间占用数据库连接
  150. if ($deleted > 0) {
  151. usleep(100000); // 休息0.1秒
  152. }
  153. } catch (\Exception $e) {
  154. DB::rollBack();
  155. $this->error("清理过程中发生错误: " . $e->getMessage());
  156. Log::error('job_runs清理失败', [
  157. 'error' => $e->getMessage(),
  158. 'cutoff_time' => $cutoffTime,
  159. 'batch_size' => $batchSize,
  160. ]);
  161. break;
  162. }
  163. } while ($deleted > 0);
  164. $progressBar->finish();
  165. $this->newLine();
  166. return $totalDeleted;
  167. }
  168. }