]> code.delx.au - bg-scripts/blob - lib/asyncsched.py
c021fc108be8d49d1ef3fdc7c8efec9f4c84cc1d
[bg-scripts] / lib / asyncsched.py
1 # Copyright 2008 James Bunton <jamesbunton@fastmail.fm>
2 # Licensed for distribution under the GPL version 2, check COPYING for details
3 # asyncore.loop() with delayed function calls
4
5 import asyncore
6 import time
7 import heapq
8
9 tasks = []
10
11 class Task(object):
12 def __init__(self, delay, func, args=[], kwargs={}):
13 self.time = time.time() + delay
14 self.func = lambda: func(*args, **kwargs)
15
16 def __cmp__(self, other):
17 return cmp(self.time, other.time)
18
19 def __call__(self):
20 f = self.func
21 self.func = None
22 if f:
23 return f()
24
25 def cancel(self):
26 assert self.func is not None
27 self.func = None
28
29 def schedule(delay, func, args=[], kwargs={}):
30 task = Task(delay, func, args, kwargs)
31 heapq.heappush(tasks, task)
32 return task
33
34 def loop(timeout=30.0):
35 while True:
36 now = time.time()
37 while tasks and tasks[0].time < now:
38 task = heapq.heappop(tasks)
39 task()
40
41 t = timeout
42 if tasks:
43 t = max(min(t, tasks[0].time - now), 0)
44
45 asyncore.poll(timeout=t)
46