Wednesday, March 14, 2007

Scheduleable Event Loop for asyncore/asynchat

Been a while since I write a blog. Below is the Python code which is quite usable to replace the default asyncore loop. It's based on Sam Rushing code which can be found at http://squirl.nightmare.com/medusa/async_sockets.html

import sys, time, asyncore

map = asyncore.socket_map

class EventLoop:
def __init__(self):
self.events = {}
self.poll = asyncore.poll3
self.__quit = None

def loop(self, timeout=30.0):
while map:
if self.__quit is True: break
now = int(time.time())
for k, v in self.events.iteritems():
if now >= k:
for o in v:
try:
o[0](*o[1][0], **o[1][1])
except:
type, value, tb = sys.exc_info()
parm = str(o[1])
logstr = "Error in Evenloop processing " + \
"scheduled task."
logstr = "Error details: %s: %s" % (type, value)
logstr = "Error details(parm): %s" % parm
logstr = "Error details(tb): %s" % \
tb.tb_frame.f_code
del self.events[k]
self.poll(timeout)

def schedule(self, delta, callback, *args, **kargs):
now = int(time.time())
if self.events.has_key(now + delta) is False:
self.events[now + delta] = []
self.events[now + delta].append((callback, (args, kargs)))

def unschedule(self, callback):
for k, v in self.events.iteritems():
for o in v:
if o[0] is callback:
del self.events[k][v][self.events[k][v].index(o)]
if len(v) == 0:
del self.events[k]

def quit(self):
self.__quit = True

No comments: