~ubuntu-branches/ubuntu/precise/gozerbot/precise

« back to all changes in this revision

Viewing changes to gozerbot/runner.py

  • Committer: Bazaar Package Importer
  • Author(s): Jeremy Malcolm
  • Date: 2008-06-02 19:26:39 UTC
  • mfrom: (1.1.3 upstream) (3.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080602192639-3rn65nx4q1sgd6sy
Tags: 0.8.1-1
New upstream release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
7
7
__copyright__ = 'this file is in the public domain'
8
8
 
9
9
from gozerbot.thr import start_new_thread
10
 
from gozerbot.generic import handle_exception, rlog
11
 
import Queue, time
12
 
 
13
 
class Runner(object):
14
 
 
15
 
    def __init__(self):
16
 
        self.queue = Queue.Queue()
17
 
        self.nr = 0
18
 
        self.dostop = False
19
 
        self.running = False
20
 
 
21
 
    def put(self, descr, func, *args, **kwargs):
22
 
        self.queue.put_nowait((descr, func, args, kwargs))
23
 
 
24
 
    def start(self):
25
 
        if not self.running:
26
 
            start_new_thread(self.run, ())
27
 
            rlog(1, 'runner', 'started runner thread')
28
 
 
29
 
    def stop(self):
30
 
        self.dostop = True
31
 
        self.running = False
32
 
        self.queue.put_nowait((None, None, None, None))
33
 
 
34
 
    def run(self):
35
 
        self.running = True
36
 
        while not self.dostop:
37
 
            (descr, func, args, kwargs) = self.queue.get()
38
 
            if self.dostop:
39
 
                break
40
 
            try:
41
 
                rlog(1, 'runner', 'running %s: %s' % (descr, str(func)))
42
 
                start = time.time()
43
 
                func(*args, **kwargs)
44
 
                elapsed = time.time() - start
45
 
                if elapsed > 1:
46
 
                    rlog(10, 'runner', 'ALERT %s %s job taking too long: %s \
 
10
from gozerbot.generic import handle_exception, rlog, lockdec
 
11
from gozerbot.threadloop import ThreadLoop
 
12
import Queue, time, thread
 
13
 
 
14
runlock = thread.allocate_lock()
 
15
locked = lockdec(runlock)
 
16
 
 
17
class Runner(ThreadLoop):
 
18
 
 
19
    @locked
 
20
    def handle(self, descr, func, *args, **kwargs):
 
21
        try:
 
22
            rlog(1, 'runner', 'running %s: %s' % (descr, str(func)))
 
23
            start = time.time()
 
24
            func(*args, **kwargs)
 
25
            elapsed = time.time() - start
 
26
            if elapsed > 1:
 
27
                rlog(10, 'runner', 'ALERT %s %s job taking too long: %s \
47
28
seconds' % (descr, str(func), elapsed))
48
 
            except Exception, ex:
49
 
                handle_exception()
50
 
        rlog(10, 'runner', 'stopped runner thread')
 
29
        except Exception, ex:
 
30
            handle_exception()
51
31
 
52
 
runner = Runner()
 
32
runner = Runner('runner')