queue.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import threading
  2. from .interface import show_message
  3. import time
  4. class Task(threading.Thread):
  5. def __init__(self, buffer, callback=None, title=None, *args, **kwargs):
  6. self.buffer = buffer
  7. self._stop = threading.Event()
  8. self.result = None
  9. self.callback = callback
  10. self.done = 0
  11. self.finished = False
  12. self.title = title
  13. threading.Thread.__init__(self, *args, **kwargs)
  14. def run(self):
  15. " Run tasks. "
  16. self._Thread__target(task=self, *self._Thread__args, **self._Thread__kwargs)
  17. # Wait for result parsing
  18. while not self.stopped():
  19. time.sleep(.2)
  20. def stop(self):
  21. " Stop task. "
  22. self._stop.set()
  23. def stopped(self):
  24. return self._stop.isSet()
  25. def stop_queue():
  26. " Stop all tasks. "
  27. for thread in threading.enumerate():
  28. if isinstance(thread, Task):
  29. thread.stop()
  30. show_message('%s stopped.' % thread.title)
  31. def add_task(target, callback=None, buffer=None, title=None, *args, **kwargs):
  32. " Add all tasks. "
  33. task = Task(buffer, title=title, target=target, callback=callback, args=args, kwargs=kwargs)
  34. task.daemon = True
  35. task.start()
  36. show_message('%s started.' % task.title)
  37. def check_task():
  38. " Check tasks for result. "
  39. for thread in threading.enumerate():
  40. if isinstance(thread, Task):
  41. if thread.finished:
  42. thread.stop()
  43. thread.callback(thread.result)
  44. else:
  45. show_message('%s %s%%' % (thread.title, thread.done))