From 504f5f6fbfe984417080484fe637898fdc1c273c Mon Sep 17 00:00:00 2001 From: Stefan Krulj Date: Sat, 6 Oct 2012 15:04:48 +0200 Subject: [PATCH] callAt changed (is now less accurate, but in the same thread as the other callbacks) cancelCall added --- brathuhn.py | 44 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/brathuhn.py b/brathuhn.py index 1666d06..ce7ca92 100644 --- a/brathuhn.py +++ b/brathuhn.py @@ -13,6 +13,8 @@ commands_private = dict() group_listeners = [] private_listeners = [] status_listeners = [] +call_ats = dict() +call_ats_id = 0 users = dict() @@ -235,11 +237,21 @@ def connect_and_join(): cl.send(xmpp.Presence(to=room_to,status=NAME+" --(brathuhn bot framework (v"+VERSION+"), type !help)")) def loop(): - global last_connect """Loop forever and handle the event-queue.""" + global last_connect + global call_ats while True: try: cl.Process(1) + to_remove = [] + for cid in call_ats: + call=call_ats[cid] + if time.time()>=call[1]: + call[0](*call[2]) + to_remove.append(cid) + for cid in to_remove: + del call_ats[cid] + except xmpp.protocol.Conflict: print "detected another connection, quitting..." sys.exit(0) @@ -248,7 +260,7 @@ def loop(): sys.exit(0) except: print "-------ERROR OCCURED-------" - exc_type, exc_value, exc_traceback = sys.exc_info() + exc_type, exc_value, exc_tracebackW = sys.exc_info() traceback.print_tb(exc_traceback, file=sys.stdout) if not cl.connected: s=MIN_CONNECT_INTERVAL-(time.time()-last_connect) @@ -258,10 +270,24 @@ def loop(): print "---------------------------" def callAt(func,_time,*args): - s=_time-time.time() - def run(): - if s>0: - time.sleep(s) - func(*args) - threading.Thread(target=run).start() - + """Call a function at given time; The call is not very exact but it is + guaranteed that it will happen after the specified time. The call happens + in the same thread, so no synchronization is needed. You can append any + number of arguments you need. Returns the call id, needed to cancel a call + + @param func -- Function to be called + @param time -- Message body""" + global call_ats + global call_ats_id + call_ats[call_ats_id]=[func,_time,args] + call_ats_id+=1 + return call_ats_id + +def cancelCall(cid): + """Remove the call from the list of pending calls + + @param cid -- The id of the call to remove + """ + if cid in call_ats: + del call_ats[cid] +