Skip to content

Instantly share code, notes, and snippets.

@TomFaulkner
Created February 11, 2018 00:31
Show Gist options
  • Save TomFaulkner/ddf8dfb15c05c7368449fd068c22e265 to your computer and use it in GitHub Desktop.
Save TomFaulkner/ddf8dfb15c05c7368449fd068c22e265 to your computer and use it in GitHub Desktop.
Monitor with a daemon thread
"""Background Loop for running a monitor process
Uses a daemon thread, so no delays in exiting.
Don't use this for things that involve writing data, as weird things
may happen if the daemon dies while writing.
Pass in an a function to call as "action"
This does what I need it for at the moment, for other uses one might
need to extend the action call to pass on parameters or *args, **kwargs.
"""
import time
import threading
class BackgroundLoop:
def __init__(self, interval=45, action=None):
"""
Don't forget to .start() the loop after init.
:param interval: time to sleep in seconds
:param action: function to run at interval
"""
self.interval = interval
self.action = action
self.thread = None
def _loop(self):
while self.should_continue:
self.action()
time.sleep(self.interval)
def start(self):
"""Start monitor execution."""
self.should_continue = True
self.thread = threading.Thread(target=self._loop, daemon=True)
self.thread.start()
def stop(self):
"""Stop monitor execution."""
self.should_continue = False
if __name__ == '__main__':
def do_the_thing():
"""Test things."""
print('hello world')
loop = BackgroundLoop(interval=5, action=do_the_thing)
loop.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment