asyncsched: Support for exiting the event loop.
authorJames Bunton <jamesbunton@delx.net.au>
Tue, 1 Jul 2008 16:54:16 +0000 (02:54 +1000)
committerJames Bunton <jamesbunton@delx.net.au>
Tue, 1 Jul 2008 16:54:16 +0000 (02:54 +1000)
lib/asyncsched.py

index c021fc1..c8b0871 100644 (file)
@@ -3,10 +3,12 @@
 # asyncore.loop() with delayed function calls
 
 import asyncore
-import time
 import heapq
+import signal
+import time
 
 tasks = []
+running = False
 
 class Task(object):
        def __init__(self, delay, func, args=[], kwargs={}):
@@ -32,7 +34,11 @@ def schedule(delay, func, args=[], kwargs={}):
        return task
 
 def loop(timeout=30.0):
-       while True:
+       global running
+       running = True
+       oldhandler = signal.signal(signal.SIGTERM, exit)
+
+       while running:
                now = time.time()
                while tasks and tasks[0].time < now:
                        task = heapq.heappop(tasks)
@@ -43,4 +49,12 @@ def loop(timeout=30.0):
                        t = max(min(t, tasks[0].time - now), 0)
 
                asyncore.poll(timeout=t)
+       
+       signal.signal(signal.SIGTERM, oldhandler)
+
+def exit(*args):
+       global running
+       running = False
+
+__all__ = ("schedule", "loop", "exit")