baseimage-tutorial-framework/lib/tfw/components/directory_monitor.py
2018-02-13 14:37:56 +01:00

46 lines
1.3 KiB
Python

from time import time, sleep
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from tfw.networking.event_handlers.server_connector import ServerUplinkConnector
from tfw.config.logs import logging
log = logging.getLogger(__name__)
class WebideReloadEventHandler(FileSystemEventHandler):
def __init__(self, rate_per_second):
super().__init__()
self.uplink = ServerUplinkConnector()
self.min_interval = 1 / float(rate_per_second)
self.last_call = time()
def on_modified(self, event):
self.limit_rate()
log.debug(event)
anchor = 'anchor_webide'
self.uplink.send(anchor, {'anchor': anchor,
'data': {'command': 'reload'}})
def limit_rate(self): #TODO: pls review me :3
since_last_call = time() - self.last_call
to_next_call = self.min_interval - since_last_call
self.last_call = time()
if to_next_call > 0:
sleep(to_next_call)
class DirectoryMonitor:
def __init__(self, directory):
self.observer = Observer()
self.observer.schedule(WebideReloadEventHandler(rate_per_second=5), directory, recursive=True)
def watch(self):
self.observer.start()
def stop(self):
self.observer.stop()
self.observer.join()