X-Git-Url: https://code.delx.au/bg-scripts/blobdiff_plain/fa352f275fdc2e7ebbb24d4c4d23a8665688b819..f71c2fbef0d1f0f7b4957ebc68f5639a533fec1a:/lib/asyncsched.py diff --git a/lib/asyncsched.py b/lib/asyncsched.py new file mode 100644 index 0000000..c021fc1 --- /dev/null +++ b/lib/asyncsched.py @@ -0,0 +1,46 @@ +# Copyright 2008 James Bunton +# Licensed for distribution under the GPL version 2, check COPYING for details +# asyncore.loop() with delayed function calls + +import asyncore +import time +import heapq + +tasks = [] + +class Task(object): + def __init__(self, delay, func, args=[], kwargs={}): + self.time = time.time() + delay + self.func = lambda: func(*args, **kwargs) + + def __cmp__(self, other): + return cmp(self.time, other.time) + + def __call__(self): + f = self.func + self.func = None + if f: + return f() + + def cancel(self): + assert self.func is not None + self.func = None + +def schedule(delay, func, args=[], kwargs={}): + task = Task(delay, func, args, kwargs) + heapq.heappush(tasks, task) + return task + +def loop(timeout=30.0): + while True: + now = time.time() + while tasks and tasks[0].time < now: + task = heapq.heappop(tasks) + task() + + t = timeout + if tasks: + t = max(min(t, tasks[0].time - now), 0) + + asyncore.poll(timeout=t) +