]> code.delx.au - bg-scripts/commitdiff
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 c021fc108be8d49d1ef3fdc7c8efec9f4c84cc1d..c8b0871e148c81c6c53aee3f48bdceeb9c22344b 100644 (file)
@@ -3,10 +3,12 @@
 # asyncore.loop() with delayed function calls
 
 import asyncore
 # asyncore.loop() with delayed function calls
 
 import asyncore
-import time
 import heapq
 import heapq
+import signal
+import time
 
 tasks = []
 
 tasks = []
+running = False
 
 class Task(object):
        def __init__(self, delay, func, args=[], kwargs={}):
 
 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):
        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)
                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)
                        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")