summaryrefslogtreecommitdiff
path: root/kafka/util.py
diff options
context:
space:
mode:
authorMahendra M <mahendra.m@gmail.com>2013-06-25 18:33:07 +0530
committerMahendra M <mahendra.m@gmail.com>2013-06-25 18:33:07 +0530
commit2ce321771825c83d51c52801d6736052289faf83 (patch)
tree9bb8e5041ac054545f36478e7870dd5e7be10bee /kafka/util.py
parent65c8eb1f9f3a309f924cf469abb16af98bbe5d6d (diff)
parent64b757868a75f47752ec26f7b5d49f84058cea40 (diff)
downloadkafka-python-2ce321771825c83d51c52801d6736052289faf83.tar.gz
Merge branch 'master' into partition
Conflicts: kafka/consumer.py
Diffstat (limited to 'kafka/util.py')
-rw-r--r--kafka/util.py40
1 files changed, 31 insertions, 9 deletions
diff --git a/kafka/util.py b/kafka/util.py
index 10bf838..11178f5 100644
--- a/kafka/util.py
+++ b/kafka/util.py
@@ -1,7 +1,7 @@
from collections import defaultdict
from itertools import groupby
import struct
-from threading import Timer
+from threading import Thread, Event
def write_int_string(s):
@@ -81,19 +81,41 @@ class ReentrantTimer(object):
t: timer interval in milliseconds
fn: a callable to invoke
+ args: tuple of args to be passed to function
+ kwargs: keyword arguments to be passed to function
"""
- def __init__(self, t, fn):
- self.timer = None
- self.t = t
+ def __init__(self, t, fn, *args, **kwargs):
+
+ if t <= 0:
+ raise ValueError('Invalid timeout value')
+
+ if not callable(fn):
+ raise ValueError('fn must be callable')
+
+ self.thread = None
+ self.t = t / 1000.0
self.fn = fn
+ self.args = args
+ self.kwargs = kwargs
+ self.active = None
+
+ def _timer(self, active):
+ while not active.wait(self.t):
+ self.fn(*self.args, **self.kwargs)
def start(self):
- if self.timer is not None:
- self.timer.cancel()
+ if self.thread is not None:
+ self.stop()
- self.timer = Timer(self.t / 1000., self.fn)
- self.timer.start()
+ self.active = Event()
+ self.thread = Thread(target=self._timer, args=(self.active,))
+ self.thread.daemon = True # So the app exits when main thread exits
+ self.thread.start()
def stop(self):
- self.timer.cancel()
+ if self.thread is None:
+ return
+
+ self.active.set()
+ self.thread.join(self.t + 1)
self.timer = None