X-Git-Url: https://code.delx.au/bg-scripts/blobdiff_plain/c3a633c99afac3a08701da1dd945e59973096a2b..fd176b77f01e67307c9899735ecac01939b2aebf:/asyncsched.py diff --git a/asyncsched.py b/asyncsched.py index cae8713..22eb788 100644 --- a/asyncsched.py +++ b/asyncsched.py @@ -11,58 +11,58 @@ tasks = [] running = False 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 __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 __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 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 + task = Task(delay, func, args, kwargs) + heapq.heappush(tasks, task) + return task def loop(timeout=30.0, use_poll=False): - global running - running = True - oldhandler = signal.signal(signal.SIGTERM, exit) + global running + running = True + oldhandler = signal.signal(signal.SIGTERM, exit) - if use_poll: - if hasattr(select, 'poll'): - poll_fun = asyncore.poll3 - else: - poll_fun = asyncore.poll2 - else: - poll_fun = asyncore.poll + if use_poll: + if hasattr(select, 'poll'): + poll_fun = asyncore.poll3 + else: + poll_fun = asyncore.poll2 + else: + poll_fun = asyncore.poll - while running: - now = time.time() - while tasks and tasks[0].time < now: - task = heapq.heappop(tasks) - task() + while running: + 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) + t = timeout + if tasks: + t = max(min(t, tasks[0].time - now), 0) - poll_fun(timeout=t) - - signal.signal(signal.SIGTERM, oldhandler) + poll_fun(timeout=t) + + signal.signal(signal.SIGTERM, oldhandler) def exit(*args): - global running - running = False + global running + running = False __all__ = ("schedule", "loop", "exit")