]> git.treefish.org Git - photosort.git/blob - src/dirtrigger.py
print observer error
[photosort.git] / src / dirtrigger.py
1 import logging
2 import threading
3 import time
4 from watchdog.events import DirDeletedEvent, FileDeletedEvent, FileSystemEventHandler
5 from watchdog.observers import Observer
6
7 class DirTrigger(FileSystemEventHandler):
8
9     def __init__(self, dir_path, cool_time, max_time):
10         self._got_event = False
11         self._last_event_time = 0.0
12         self._last_reset_time = 0.0
13         self._cool_time = cool_time
14         self._max_time = max_time
15         self._lock = threading.Lock()
16         self._observer = Observer()
17         self._observer.schedule(self, path=dir_path, recursive=True)
18
19     def start(self):
20         try:
21             self._observer.start()
22         except Exception as e:
23             logging.warning("Error starting file observer for %s: %s", dir_path, str(e))
24
25     def stop(self):
26         self._observer.stop()
27
28     def is_triggering(self):
29         self._lock.acquire()
30         try:
31             now = time.time()
32             return ( self._got_event and
33                      (now - self._last_event_time > self._cool_time) ) or \
34                      now - self._last_reset_time > self._max_time
35         finally:
36             self._lock.release()
37
38     def reset(self):
39         self._lock.acquire()
40         try:
41             self._got_event = False
42             self._last_reset_time = time.time()
43         finally:
44             self._lock.release()
45
46     def on_any_event(self, event):
47         if event.event_type == FileDeletedEvent or event.event_type == DirDeletedEvent:
48             return
49
50         self._lock.acquire()
51         try:
52             self._got_event = True
53             self._last_event_time = time.time()
54         finally:
55             self._lock.release()