import os
import shutil
import hashlib
import schedule
import time
from datetime import datetime, timedelta
# === CONFIG ===
TEMP_DIRS = ["temp"]
LOG_DIRS = ["logs"]
DUPLICATE_SCAN_DIRS = ["temp", "logs"]
LOG_EXPIRY_DAYS = 7
# === 1. Delete temp files ===
def clean_temp_folders():
print("๐งน Cleaning temp folders...")
for folder in TEMP_DIRS:
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.remove(file_path)
print(f"Deleted file: {file_path}")
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
print(f"Deleted folder: {file_path}")
except Exception as e:
print(f"❌ Failed to delete {file_path}: {e}")
# === 2. Delete old logs ===
def delete_old_logs():
print("๐ Deleting old logs...")
for folder in LOG_DIRS:
for root, dirs, files in os.walk(folder):
for file in files:
file_path = os.path.join(root, file)
try:
file_time = datetime.fromtimestamp(os.path.getmtime(file_path))
if datetime.now() - file_time > timedelta(days=LOG_EXPIRY_DAYS):
os.remove(file_path)
print(f"๐️ Removed old log: {file_path}")
except Exception as e:
print(f"❌ Error checking {file_path}: {e}")
# === 3. Delete duplicate files ===
def delete_duplicates():
print("๐ Searching for duplicates...")
hashes = {}
for folder in DUPLICATE_SCAN_DIRS:
for root, _, files in os.walk(folder):
for file in files:
path = os.path.join(root, file)
try:
with open(path, 'rb') as f:
file_hash = hashlib.md5(f.read()).hexdigest()
if file_hash in hashes:
os.remove(path)
print(f"❌ Duplicate removed: {path}")
else:
hashes[file_hash] = path
except Exception as e:
print(f"❌ Error reading {path}: {e}")
# === 4. Master cleanup function ===
def run_cleanup():
print(f"\n๐ง Running system cleanup @ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
clean_temp_folders()
delete_old_logs()
delete_duplicates()
print("✅ Cleanup complete.")
# === 5. Scheduler ===
schedule.every().sunday.at("08:00").do(run_cleanup)
print("๐ System Cleanup Scheduler started... (Press Ctrl+C to exit)")
run_cleanup() # Run once on start
while True:
schedule.run_pending()
time.sleep(60)
No comments:
Post a Comment