X-Git-Url: http://git.ipfire.org/?p=oddments%2Fcappie.git;a=blobdiff_plain;f=cappie%2Fqueue.py;fp=cappie%2Fqueue.py;h=e2d0dd6486599067895814c65c50fd26d76913ba;hp=0000000000000000000000000000000000000000;hb=534780507041d0f1058b11c7c74c0f89a2bc6e37;hpb=39fedabd85a5d9703e7b65204976ee872679ee27 diff --git a/cappie/queue.py b/cappie/queue.py new file mode 100644 index 0000000..e2d0dd6 --- /dev/null +++ b/cappie/queue.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +############################################################################### +# # +# Cappie # +# Copyright (C) 2010 Michael Tremer # +# # +# This program is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# This program is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +############################################################################### + +import time + +from threading import Thread + +from errors import * + +class Queue(Thread): + heartbeat = 1.0 + maxitems = 100 + + def __init__(self, log): + Thread.__init__(self) + + self.log = log + + self.__running = True + self.__queue = [] + + def __len__(self): + return self.length + + def add(self, event): + if self.length > self.maxitems: + raise QueueFullError, "Cannot queue new event." + + self.__queue.append(event) + + @property + def length(self): + return len(self.__queue) + + def run(self): + self.log.debug("Started event queue") + + while self.__running or self.__queue: + if not self.__queue: + #self.log.debug("Queue sleeping for %s seconds" % self.heartbeat) + time.sleep(self.heartbeat) + continue + + event = self.__queue.pop(0) + self.log.debug("Processing queue event: %s" % event) + try: + event.run() + except EventException, e: + self.log.error("Catched event exception: %s" % e) + + def shutdown(self): + self.__running = False + self.log.debug("Shutting down queue") + self.log.debug("%d events in queue left" % len(self.__queue)) + + # Wait until queue handled all events + self.join()