CleanExpiredTokens.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\Log;
  5. use Laravel\Sanctum\PersonalAccessToken;
  6. class CleanExpiredTokens extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'sanctum:clean-expired-tokens';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = '定时清理过期的token';
  20. /**
  21. * Execute the console command.
  22. *
  23. * @return int
  24. */
  25. public function handle()
  26. {
  27. try {
  28. while (true) {
  29. // 过期时间
  30. $expirationTime = now()->subMinutes(config('sanctum.expiration'));
  31. // 删除所有过期的 token
  32. PersonalAccessToken::where('created_at', '<', $expirationTime)->delete();
  33. // 等待24小时
  34. sleep(86400);
  35. }
  36. } catch (\Exception $e) {
  37. Log::error($this->description . ' 程序异常: ' . $e->getMessage());
  38. throw $e;
  39. }
  40. }
  41. }