]> 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
17         try:
18             self._observer = Observer()
19             self._observer.schedule(self, path=dir_path, recursive=True)
20         except Exception as e:
21             logging.error("Error creating file observer for %s: %s", dir_path, str(e))
22             raise e
23
24     def start(self):
25         self._observer.start()
26
27     def stop(self):
28         self._observer.stop()
29
30     def is_triggering(self):
31         self._lock.acquire()
32         try:
33             now = time.time()
34             return ( self._got_event and
35                      (now - self._last_event_time > self._cool_time) ) or \
36                      now - self._last_reset_time > self._max_time
37         finally:
38             self._lock.release()
39
40     def reset(self):
41         self._lock.acquire()
42         try:
43             self._got_event = False
44             self._last_reset_time = time.time()
45         finally:
46             self._lock.release()
47
48     def on_any_event(self, event):
49         if event.event_type == FileDeletedEvent or event.event_type == DirDeletedEvent:
50             return
51
52         self._lock.acquire()
53         try:
54             self._got_event = True
55             self._last_event_time = time.time()
56         finally:
57             self._lock.release()