1
# gozerbot/threads/threadloop.py
5
""" class to implement start/stoppable threads. """
7
__copyright__ = 'this file is in the public domain'
10
from gozerbot.utils.log import rlog
11
from gozerbot.config import config
12
from gozerbot.utils.exception import handle_exception
15
from thr import start_new_thread
20
class ThreadLoop(object):
22
""" implement startable/stoppable threads. """
24
def __init__(self, name="", queue=None):
25
self.name = name or 'idle'
29
self.queue = queue or Queue.Queue()
30
self.nowrunning = "none"
33
rlog(0, "threadloop", 'starting threadloop')
34
while not self.stopped:
38
data = self.queue.get_nowait()
50
rlog(0, self.name, 'running %s' % str(data))
52
except Exception, ex: handle_exception()
55
rlog(0, self.name, 'stopping threadloop')
59
""" put data on task queue. """
61
self.queue.put_nowait(data)
65
""" start the thread. """
68
start_new_thread(self._loop, ())
72
""" stop the thread. """
78
def handle(self, *args, **kwargs):
80
""" overload this. """
84
class RunnerLoop(ThreadLoop):
86
""" dedicated threadloop for bot commands/callbacks. """
90
rlog(0, "runnerloop", 'starting threadloop')
93
while not self.stopped:
96
data = self.queue.get()
109
self.nowrunning = data[0]
110
rlog(0, 'runnerloop', 'now running %s' % self.nowrunning)
114
rlog(0, 'runnerloop', 'stopping threadloop')
116
class ThreadSleeper(ThreadLoop):
118
def __init__(self, name="", timeout=1800):
119
ThreadLoop.__init__(self, name)
120
self.timeout = timeout
123
rlog(0, 'threadsleeper', 'starting threadloop')
126
while not self.stopped:
127
time.sleep(self.timeout)
131
rlog(-1, self.name, 'running')
135
rlog(0, 'threadsleeper', 'stopping threadloop')