Guest User

Untitled

a guest
Feb 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. """Background Loop for running a monitor process
  2.  
  3. Uses a daemon thread, so no delays in exiting.
  4. Don't use this for things that involve writing data, as weird things
  5. may happen if the daemon dies while writing.
  6.  
  7. Pass in an a function to call as "action"
  8.  
  9. This does what I need it for at the moment, for other uses one might
  10. need to extend the action call to pass on parameters or *args, **kwargs.
  11. """
  12. import time
  13. import threading
  14.  
  15.  
  16. class BackgroundLoop:
  17. def __init__(self, interval=45, action=None):
  18. """
  19. Don't forget to .start() the loop after init.
  20.  
  21. :param interval: time to sleep in seconds
  22. :param action: function to run at interval
  23. """
  24. self.interval = interval
  25. self.action = action
  26. self.thread = None
  27.  
  28. def _loop(self):
  29. while self.should_continue:
  30. self.action()
  31. time.sleep(self.interval)
  32.  
  33. def start(self):
  34. """Start monitor execution."""
  35. self.should_continue = True
  36. self.thread = threading.Thread(target=self._loop, daemon=True)
  37. self.thread.start()
  38.  
  39. def stop(self):
  40. """Stop monitor execution."""
  41. self.should_continue = False
  42.  
  43.  
  44. if __name__ == '__main__':
  45. def do_the_thing():
  46. """Test things."""
  47. print('hello world')
  48.  
  49. loop = BackgroundLoop(interval=5, action=do_the_thing)
  50. loop.start()
Add Comment
Please, Sign In to add comment