config_watcher.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import os
  5. from datetime import datetime
  6. from module.config.utils import filepath_config, DEFAULT_TIME
  7. from module.logger import logger
  8. class ConfigWatcher:
  9. """
  10. 监视特定配置文件修改的功能。
  11. 它跟踪了初始修改时间,(start_mtime)
  12. 并提供了方法来检查文件是否被修改(should_reload)
  13. 和获取当前修改时间(get_mtime)。
  14. """
  15. config_name = 'script'
  16. start_mtime = DEFAULT_TIME
  17. def start_watching(self) -> None:
  18. self.start_mtime = self.get_mtime()
  19. def get_mtime(self) -> datetime:
  20. """
  21. Last modify time of the file
  22. """
  23. timestamp = os.stat(filepath_config(self.config_name)).st_mtime
  24. mtime = datetime.fromtimestamp(timestamp).replace(microsecond=0)
  25. return mtime
  26. def should_reload(self) -> bool:
  27. """
  28. Returns:
  29. bool: Whether the file has been modified and configs should reload
  30. """
  31. mtime = self.get_mtime()
  32. if mtime > self.start_mtime:
  33. logger.info(f'Config "{self.config_name}" changed at {mtime}')
  34. return True
  35. else:
  36. return False