Skip to content

Instantly share code, notes, and snippets.

@adoc
Created April 27, 2014 16:20
Show Gist options
  • Save adoc/11349626 to your computer and use it in GitHub Desktop.
Save adoc/11349626 to your computer and use it in GitHub Desktop.
threadutils: Threading utility functions.
import time
import threading
THROTTLE = 0.01
class KillableThread(threading.Thread):
"""Subclass of threading.Thread with kill signal functionality.
"""
def __init__(self, *args, **kwa):
"""Constructs a KillableThread object."""
threading.Thread.__init__(self, *args, **kwa)
self.__kill_event = threading.Event()
def kill(self):
"""Sets kill signal for the thread.
"""
self.__kill_event.set()
def __iskilled(self):
return self.__kill_event.isSet()
@property
def iskilled(self):
"""Returns True if this thread has been sent a kill signal.
"""
return self.__iskilled()
class RepeatingTimer(KillableThread):
"""Simple repeating timer.
param:pass_timer - pass Timer instance to the callback.
"""
def __init__(self, interval, callback, pass_timer=False, halt_on_exc=False):
KillableThread.__init__(self)
self.__interval = interval
self.__callback = callback
self.__pass_timer = pass_timer
self.__halt_on_exc = halt_on_exc
self.__timer = None
# Protected props.
@property
def interval(self):
return self.__interval
@property
def pass_timer(self):
return self.__pass_timer
@property
def halt_on_exc(self):
return self.__halt_on_exc
def callback(self):
try:
if self.pass_timer is True:
return self.__callback(self)
else:
return self.__callback()
except:
if self.halt_on_exc:
self.cancel()
raise
def run(self):
# Note: Instead of joining the timer, we handle our own loop
# that watches it.
while self.iskilled is not True:
if self.__timer is None or self.__timer.is_alive() is False:
self.__timer = threading.Timer(self.interval, self.callback)
self.__timer.start()
time.sleep(THROTTLE)
def cancel(self):
if self.__timer is not None:
self.__timer.cancel()
self.kill()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment