-
Notifications
You must be signed in to change notification settings - Fork 1
/
id_cleaner.py
66 lines (58 loc) · 2.45 KB
/
id_cleaner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
import time
import shutil
import logging
from datetime import datetime, timedelta
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Configure logging
FORMAT = "%(asctime)s: %(levelname)s: %(message)s"
logging.basicConfig(filename="logs.log", level=logging.INFO, format=FORMAT)
STDERRLOGGER = logging.StreamHandler()
STDERRLOGGER.setFormatter(logging.Formatter(FORMAT))
logging.getLogger().addHandler(STDERRLOGGER)
class DirectoryCleanupHandler(FileSystemEventHandler):
def __init__(self, threshold_minutes=60, check_interval_minutes=5):
self.threshold = timedelta(minutes=threshold_minutes)
self.check_interval = check_interval_minutes * 60
self.last_check_time = datetime.now()
def on_modified(self, event):
if event.is_directory and event.src_path.startswith("_id_"):
logging.info(f"Detected modification in directory: {event.src_path}")
self.cleanup_directories()
def cleanup_directories(self):
now = datetime.now()
for dirpath, _, _ in os.walk("."):
if os.path.basename(dirpath).startswith("_id_"):
try:
mtime = os.path.getmtime(dirpath)
mtime_dt = datetime.fromtimestamp(mtime)
if now - mtime_dt > self.threshold:
logging.info(f"Deleting directory: {dirpath}")
shutil.rmtree(dirpath)
except Exception as e:
logging.error(f"Error deleting {dirpath}: {e}")
def start_cleanup_loop(self):
while True:
current_time = datetime.now()
if (
current_time - self.last_check_time
).total_seconds() >= self.check_interval:
logging.info("Woke up to check directories")
self.cleanup_directories()
self.last_check_time = current_time
time.sleep(self.check_interval)
if __name__ == "__main__":
logging.info("Starting directory cleanup script")
event_handler = DirectoryCleanupHandler(
threshold_minutes=60, check_interval_minutes=30
)
observer = Observer()
observer.schedule(event_handler, path=".", recursive=True)
observer.start()
try:
event_handler.start_cleanup_loop()
except KeyboardInterrupt:
logging.info("Stopping directory cleanup script due to keyboard interrupt")
observer.stop()
observer.join()