]> git.ipfire.org Git - oddments/cappie.git/blame - cappie/queue.py
Add database interface to queue class.
[oddments/cappie.git] / cappie / queue.py
CommitLineData
53478050
MT
1#!/usr/bin/python
2###############################################################################
3# #
4# Cappie #
5# Copyright (C) 2010 Michael Tremer #
6# #
7# This program is free software: you can redistribute it and/or modify #
8# it under the terms of the GNU General Public License as published by #
9# the Free Software Foundation, either version 3 of the License, or #
10# (at your option) any later version. #
11# #
12# This program is distributed in the hope that it will be useful, #
13# but WITHOUT ANY WARRANTY; without even the implied warranty of #
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15# GNU General Public License for more details. #
16# #
17# You should have received a copy of the GNU General Public License #
18# along with this program. If not, see <http://www.gnu.org/licenses/>. #
19# #
20###############################################################################
21
22import time
23
24from threading import Thread
25
af1f4801 26from database import Database
53478050
MT
27from errors import *
28
29class Queue(Thread):
30 heartbeat = 1.0
31 maxitems = 100
32
33 def __init__(self, log):
34 Thread.__init__(self)
35
36 self.log = log
37
38 self.__running = True
39 self.__queue = []
40
af1f4801
MT
41 self.db = Database(log)
42
53478050
MT
43 def __len__(self):
44 return self.length
45
46 def add(self, event):
47 if self.length > self.maxitems:
48 raise QueueFullError, "Cannot queue new event."
49
50 self.__queue.append(event)
51
52 @property
53 def length(self):
54 return len(self.__queue)
55
56 def run(self):
57 self.log.debug("Started event queue")
58
af1f4801
MT
59 self.db.open()
60
53478050
MT
61 while self.__running or self.__queue:
62 if not self.__queue:
63 #self.log.debug("Queue sleeping for %s seconds" % self.heartbeat)
64 time.sleep(self.heartbeat)
65 continue
66
67 event = self.__queue.pop(0)
68 self.log.debug("Processing queue event: %s" % event)
69 try:
70 event.run()
71 except EventException, e:
72 self.log.error("Catched event exception: %s" % e)
73
af1f4801
MT
74 self.db.close()
75
53478050
MT
76 def shutdown(self):
77 self.__running = False
78 self.log.debug("Shutting down queue")
79 self.log.debug("%d events in queue left" % len(self.__queue))
80
81 # Wait until queue handled all events
82 self.join()