Package logilab :: Package common :: Module tasksqueue
[frames] | no frames]

Source Code for Module logilab.common.tasksqueue

 1  """Prioritized tasks queue 
 2   
 3  :organization: Logilab 
 4  :copyright: 2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved. 
 5  :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr 
 6  """ 
 7  __docformat__ = "restructuredtext en" 
 8   
 9  from bisect import insort_left 
10  from Queue import Queue 
11   
12  LOW = 0 
13  MEDIUM = 10 
14  HIGH = 100 
15   
16  REVERSE_PRIORITY = { 
17      0: 'LOW', 
18      10: 'MEDIUM', 
19      100: 'HIGH' 
20      } 
21   
22   
23 -class PrioritizedTasksQueue(Queue):
24
25 - def _init(self, maxsize):
26 """Initialize the queue representation""" 27 self.maxsize = maxsize 28 # ordered list of task, from the lowest to the highest priority 29 self.queue = []
30
31 - def _put(self, item):
32 """Put a new item in the queue""" 33 for i, task in enumerate(self.queue): 34 # equivalent task 35 if task == item: 36 # if new task has a higher priority, remove the one already 37 # queued so the new priority will be considered 38 if task < item: 39 item.merge(task) 40 del self.queue[i] 41 break 42 # else keep it so current order is kept 43 task.merge(item) 44 return 45 insort_left(self.queue, item)
46
47 - def _get(self):
48 """Get an item from the queue""" 49 return self.queue.pop()
50
51 - def __iter__(self):
52 return iter(self.queue)
53
54 - def remove(self, tid):
55 """remove a specific task from the queue""" 56 # XXX acquire lock 57 for i, task in enumerate(self): 58 if task.id == tid: 59 self.queue.pop(i) 60 return 61 raise ValueError('not task of id %s in queue' % tid)
62
63 -class Task(object):
64 - def __init__(self, tid, priority=LOW):
65 # task id 66 self.id = tid 67 # task priority 68 self.priority = priority
69
70 - def __repr__(self):
71 return '<Task %s @%#x>' % (self.id, id(self))
72
73 - def __cmp__(self, other):
74 return cmp(self.priority, other.priority)
75
76 - def __eq__(self, other):
77 return self.id == other.id
78
79 - def merge(self, other):
80 pass
81