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

Source Code for Module logilab.common.tasksqueue

 1  # copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. 
 2  # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr 
 3  # 
 4  # This file is part of logilab-common. 
 5  # 
 6  # logilab-common is free software: you can redistribute it and/or modify it under 
 7  # the terms of the GNU Lesser General Public License as published by the Free 
 8  # Software Foundation, either version 2.1 of the License, or (at your option) any 
 9  # later version. 
10  # 
11  # logilab-common is distributed in the hope that it will be useful, but WITHOUT 
12  # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
13  # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more 
14  # details. 
15  # 
16  # You should have received a copy of the GNU Lesser General Public License along 
17  # with logilab-common.  If not, see <http://www.gnu.org/licenses/>. 
18  """Prioritized tasks queue 
19   
20  :organization: Logilab 
21   
22   
23  """ 
24  __docformat__ = "restructuredtext en" 
25   
26  from bisect import insort_left 
27  from Queue import Queue 
28   
29  LOW = 0 
30  MEDIUM = 10 
31  HIGH = 100 
32   
33  REVERSE_PRIORITY = { 
34      0: 'LOW', 
35      10: 'MEDIUM', 
36      100: 'HIGH' 
37      } 
38   
39   
40 -class PrioritizedTasksQueue(Queue):
41
42 - def _init(self, maxsize):
43 """Initialize the queue representation""" 44 self.maxsize = maxsize 45 # ordered list of task, from the lowest to the highest priority 46 self.queue = []
47
48 - def _put(self, item):
49 """Put a new item in the queue""" 50 for i, task in enumerate(self.queue): 51 # equivalent task 52 if task == item: 53 # if new task has a higher priority, remove the one already 54 # queued so the new priority will be considered 55 if task < item: 56 item.merge(task) 57 del self.queue[i] 58 break 59 # else keep it so current order is kept 60 task.merge(item) 61 return 62 insort_left(self.queue, item)
63
64 - def _get(self):
65 """Get an item from the queue""" 66 return self.queue.pop()
67
68 - def __iter__(self):
69 return iter(self.queue)
70
71 - def remove(self, tid):
72 """remove a specific task from the queue""" 73 # XXX acquire lock 74 for i, task in enumerate(self): 75 if task.id == tid: 76 self.queue.pop(i) 77 return 78 raise ValueError('not task of id %s in queue' % tid)
79
80 -class Task(object):
81 - def __init__(self, tid, priority=LOW):
82 # task id 83 self.id = tid 84 # task priority 85 self.priority = priority
86
87 - def __repr__(self):
88 return '<Task %s @%#x>' % (self.id, id(self))
89
90 - def __cmp__(self, other):
91 return cmp(self.priority, other.priority)
92
93 - def __eq__(self, other):
94 return self.id == other.id
95
96 - def merge(self, other):
97 pass
98