Skip to content

Instantly share code, notes, and snippets.

@marceljanerfont
Created September 21, 2017 10:24
Show Gist options
  • Save marceljanerfont/9636546e3c9a1bf5eea085462da93e60 to your computer and use it in GitHub Desktop.
Save marceljanerfont/9636546e3c9a1bf5eea085462da93e60 to your computer and use it in GitHub Desktop.
Stoppable worker thread
# -*- coding: utf-8 -*-
import threading
import time
class Worker(object):
def __init__(self):
self._stop_event = threading.Event()
self._thread = threading.Thread(target=self.run, args=())
# important otherwise never stops when run() gets stuck!!
self._thread.daemon = True
self._thread.start()
def run(self):
while not self._stop_event.is_set():
print("I'm running..")
self._stop_event.wait(1)
time.sleep(5)
print("Exiting!")
def stop(self):
print("Stopping...")
self._stop_event.set()
self._thread.join(3) # sec
if self._thread.is_alive():
print("ERROR Stopping thread, it is alive!!")
else:
print("Stopped")
self._thread = None
print("Killed")
worker = Worker()
time.sleep(5)
worker.stop()
print("bye!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment