Skip to content

Instantly share code, notes, and snippets.

@enaeseth
Created March 18, 2013 21:09
Show Gist options
  • Save enaeseth/5190833 to your computer and use it in GitHub Desktop.
Save enaeseth/5190833 to your computer and use it in GitHub Desktop.
"""
Interruptible worker pattern
"""
import threading
class Worker(object):
def __init__(self):
self._running = False
self._wakeup = threading.Condition()
def start(self):
with self._wakeup:
if self._running:
raise RuntimeError
self._running = True
self._thread = threading.Thread(target=self._run)
self._thread.start()
def stop(self):
with self._wakeup:
if not self._running:
raise RuntimeError
self._running = False
self._wakeup.notify_all()
self._thread.join()
def _run(self):
while self._running:
# Do our task
self.do_actual_work()
# Sleep for five seconds before trying to do more work
with self._wakeup:
self._wakeup.wait(5.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment