Skip to main content

Maintenance

Automated Maintenance Tasks

Database Maintenance

php

<?php
class DatabaseMaintenance
{
private PDO $db;
private Logger $logger;
public function __construct()
{
$this->db = DatabaseConnection::getInstance();
$this->logger = new Logger('/var/log/maintenance.log');
}
public function optimizeTables(): void
{
$tables = $this->getTables();
foreach ($tables as $table) {
try {
$this->db->exec("OPTIMIZE TABLE {$table}");
$this->logger->info("Optimized table: {$table}");
} catch (Exception $e) {
$this->logger->error("Failed to optimize table {$table}: " . $e->getMessage());
}
}
}
public function cleanupOldRecords(): void
{
$cleanupRules = [
'logs' => 'created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)',
'sessions' => 'last_activity < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 24 HOUR))',
'temp_files' => 'created_at < DATE_SUB(NOW(), INTERVAL 1 DAY)'
];
foreach ($cleanupRules as $table => $condition) {
try {
$stmt = $this->db->prepare("DELETE FROM {$table} WHERE {$condition}");
$stmt->execute();
$affected = $stmt->rowCount();
$this->logger->info("Cleaned up {$affected} records from {$table}");
} catch (Exception $e) {
$this->logger->error("Failed to cleanup {$table}: " . $e->getMessage());
}
}
}
private function getTables(): array
{
$stmt = $this->db->query('SHOW TABLES');
return $stmt->fetchAll(PDO::FETCH_COLUMN);
}
}

Cache Maintenance

php

<?php
class CacheMaintenance
{
private Redis $redis;
private Logger $logger;
public function __construct()
{
$this->redis = RedisConnection::getInstance();
$this->logger = new Logger('/var/log/maintenance.log');
}
public function clearExpiredKeys(): void
{
$info = $this->redis->info('keyspace');
$this->logger->info('Cache cleanup completed', ['keyspace_info' => $info]);
}
public function optimizeMemory(): void
{
$memoryBefore = $this->redis->info('memory')['used_memory'];
$this->redis->bgRewriteAOF();
$memoryAfter = $this->redis->info('memory')['used_memory'];
$this->logger->info('Memory optimization completed', [
'memory_before' => $memoryBefore,
'memory_after' => $memoryAfter,
'saved' => $memoryBefore - $memoryAfter
]);
}
}

Scheduled Maintenance Script

bash

#!/bin/bash
# maintenance.sh - Automated maintenance script
LOG_FILE="/var/log/maintenance.log"
PHP_SCRIPT="/var/www/html/maintenance.php"
echo "$(date): Starting maintenance tasks" >> $LOG_FILE
# Run PHP maintenance script
/usr/bin/php $PHP_SCRIPT >> $LOG_FILE 2>&1
# Clear application logs older than 30 days
find /var/log/app -name "*.log" -mtime +30 -delete
# Clear temporary files
find /tmp -name "php*" -mtime +1 -delete
# Restart PHP-FPM if memory usage is high
MEMORY_USAGE=$(ps aux | grep php-fpm | awk '{sum+=$6} END {print sum/1024}')
if (( $(echo "$MEMORY_USAGE > 1024" | bc -l) )); then
systemctl restart php8.1-fpm
echo "$(date): Restarted PHP-FPM due to high memory usage: ${MEMORY_USAGE}MB" >> $LOG_FILE
fi
echo "$(date): Maintenance tasks completed" >> $LOG_FILE

Crontab Configuration

bash
# Add to crontab with: crontab -e
# Daily maintenance at 2 AM
0 2 * * * /usr/local/bin/maintenance.sh
# Weekly database optimization on Sundays at 3 AM
0 3 * * 0 /usr/bin/php /var/www/html/scripts/database_optimize.php
# Clear cache every 6 hours
0 */6 * * * /usr/bin/php /var/www/html/scripts/cache_cleanup.php
# Monitor disk space every hour
0 * * * * /usr/local/bin/check_disk_space.sh