1 # Written by Arno Bakker
2 # see LICENSE.txt for license information
4 # TimedTaskQueue is a server that executes tasks on behalf of e.g. the GUI that
5 # are too time consuming to be run by the actual GUI Thread (MainThread). Note
6 # that you still need to delegate the actual updating of the GUI to the
7 # MainThread via the wx.CallAfter mechanism.
11 from threading import Thread,Condition
12 from traceback import print_exc,print_stack
21 def __init__(self,nameprefix="TimedTaskQueue",isDaemon=True):
22 self.cond = Condition()
24 self.count = 0.0 # serves to keep task that were scheduled at the same time in FIFO order
25 self.thread = Thread(target = self.run)
26 self.thread.setDaemon(isDaemon)
27 self.thread.setName( nameprefix+self.thread.getName() )
30 def add_task(self,task,t=0,id=None):
31 """ t parameter is now usable, unlike before.
32 If id is given, all the existing tasks with the same id will be removed
33 before inserting this task
42 print >>sys.stderr,"ttqueue: ADD EVENT",t,task
44 if id != None: # remove all redundant tasks
45 self.queue = filter(lambda item:item[2]!=id, self.queue)
46 self.queue.append((when,self.count,task,id))
52 """ Run by server thread """
59 while len(self.queue) == 0 or flag:
62 # Wait until something is queued
65 # Wait till first event is due
66 self.cond.wait(timeout)
67 # A new event was added or an event is due
70 (when,count,task,id) = self.queue[0]
72 print >>sys.stderr,"ttqueue: EVENT IN QUEUE",when,task
75 # Event not due, wait some more
77 print >>sys.stderr,"ttqueue: EVENT NOT TILL",when-now
83 print >>sys.stderr,"ttqueue: EVENT DUE"
88 # Execute task outside lock
90 # 'stop' and 'quit' are only used for unit test
94 if len(self.queue) == 0:
97 (when,count,task,id) = self.queue[-1]
99 self.add_task('quit',t)