Created
November 21, 2016 21:37
-
-
Save asfaltboy/6286d792b79d155adbc3a125d24a4b81 to your computer and use it in GitHub Desktop.
example of exception raised in daemon thread
This file contains hidden or 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
from datetime import datetime | |
from Queue import Queue | |
import threading | |
import time | |
def worker(q): | |
while True: | |
item = q.get() | |
if isinstance(item, Exception): | |
raise item | |
print('Working on %s...' % item) | |
time.sleep(0.1) | |
q.task_done() | |
def heartbeat(): | |
the_queue = Queue() | |
# create the thread pool | |
for n in range(5): | |
t = threading.Thread(target=worker, args=(the_queue,)) | |
t.setDaemon(True) | |
t.start() | |
while True: | |
# mark the start time | |
start_time = datetime.utcnow() | |
# use Django ORM to get a list of devices | |
for device in range(20) + [Exception('Error!')]: | |
the_queue.put(device) | |
# wait for workers to deal with things | |
the_queue.join() | |
# mark the end time | |
end_time = datetime.utcnow() | |
print('finished in %i' % (end_time - start_time).total_seconds()) | |
time.sleep(0.5) | |
if __name__ == "__main__": | |
heartbeat() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment