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