Files
FendxPHP/app/Job/CleanupJob.php

103 lines
2.6 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Job;
use Fendx\Core\Annotation\Service;
use Fendx\Job\Annotation\Scheduled;
use Fendx\Log\Logger;
#[Service]
class CleanupJob
{
#[Scheduled('0 2 * * *', 'Daily cleanup at 2 AM')]
public function dailyCleanup(): void
{
Logger::info('Starting daily cleanup job');
// 清理过期日志文件
$this->cleanupOldLogs();
// 清理临时文件
$this->cleanupTempFiles();
// 清理过期缓存
$this->cleanupExpiredCache();
Logger::info('Daily cleanup job completed');
}
#[Scheduled('*/5 * * * *', 'Every 5 minutes')]
public function healthCheck(): void
{
// 检查系统健康状态
$healthy = $this->checkSystemHealth();
if (!$healthy) {
Logger::warning('System health check failed');
}
}
private function cleanupOldLogs(): void
{
$logDir = dirname(__DIR__, 2) . '/runtime/logs';
$maxAge = 30 * 24 * 60 * 60; // 30天
if (is_dir($logDir)) {
$files = glob($logDir . '/*.log');
foreach ($files as $file) {
if (filemtime($file) < time() - $maxAge) {
unlink($file);
Logger::info("Deleted old log file: $file");
}
}
}
}
private function cleanupTempFiles(): void
{
$tempDir = dirname(__DIR__, 2) . '/runtime/temp';
$maxAge = 24 * 60 * 60; // 24小时
if (is_dir($tempDir)) {
$files = glob($tempDir . '/*');
foreach ($files as $file) {
if (is_file($file) && filemtime($file) < time() - $maxAge) {
unlink($file);
Logger::info("Deleted temp file: $file");
}
}
}
}
private function cleanupExpiredCache(): void
{
// 这里可以添加Redis缓存清理逻辑
Logger::info('Cache cleanup completed');
}
private function checkSystemHealth(): bool
{
// 检查数据库连接
try {
$pdo = new \PDO('mysql:host=127.0.0.1;dbname=fendx', 'root', '');
$pdo->query('SELECT 1');
} catch (\Exception $e) {
return false;
}
// 检查Redis连接
try {
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->ping();
} catch (\Exception $e) {
return false;
}
return true;
}
}