refactor(online-status): consolidate updates and add cleanup command

This commit is contained in:
xboard
2025-09-15 20:32:22 +08:00
parent cd8a8ecf58
commit 843c5af4c2
5 changed files with 163 additions and 74 deletions
@@ -0,0 +1,52 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\Log;
class CleanupExpiredOnlineStatus extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cleanup:expired-online-status';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Reset online_count to 0 for users stale for 5+ minutes';
/**
* Execute the console command.
*/
public function handle()
{
try {
$affected = 0;
User::query()
->where('online_count', '>', 0)
->where('last_online_at', '<', now()->subMinutes(5))
->chunkById(1000, function ($users) use (&$affected) {
if ($users->isEmpty()) {
return;
}
$count = User::whereIn('id', $users->pluck('id'))
->update(['online_count' => 0]);
$affected += $count;
}, 'id');
$this->info("Expired online status cleaned. Affected: {$affected}");
return self::SUCCESS;
} catch (\Throwable $e) {
Log::error('CleanupExpiredOnlineStatus failed', ['error' => $e->getMessage()]);
$this->error('Cleanup failed: ' . $e->getMessage());
return self::FAILURE;
}
}
}
+1 -4
View File
@@ -46,10 +46,7 @@ class Kernel extends ConsoleKernel
// if (env('ENABLE_AUTO_BACKUP_AND_UPDATE', false)) {
// $schedule->command('backup:database', ['true'])->daily()->onOneServer();
// }
// 每分钟清理过期的在线状态
$schedule->call(function () {
app(UserOnlineService::class)->cleanExpiredOnlineStatus();
})->everyMinute()->name('cleanup:expired-online-status')->onOneServer();
$schedule->command('cleanup:expired-online-status')->everyMinute()->onOneServer()->withoutOverlapping(4);
app(PluginManager::class)->registerPluginSchedules($schedule);