Created
September 21, 2017 10:24
-
-
Save marceljanerfont/9636546e3c9a1bf5eea085462da93e60 to your computer and use it in GitHub Desktop.
Stoppable worker thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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