]>
code.delx.au - bg-scripts/blob - 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
5 import asyncore
, select
14 def __init__(self
, delay
, func
, args
=[], kwargs
={}):
15 self
.time
= time
.time() + delay
16 self
.func
= lambda: func(*args
, **kwargs
)
18 def __cmp__(self
, other
):
19 return cmp(self
.time
, other
.time
)
28 assert self
.func
is not None
31 def schedule(delay
, func
, args
=[], kwargs
={}):
32 task
= Task(delay
, func
, args
, kwargs
)
33 heapq
.heappush(tasks
, task
)
36 def loop(timeout
=30.0, use_poll
=False):
39 oldhandler
= signal
.signal(signal
.SIGTERM
, exit
)
42 if hasattr(select
, 'poll'):
43 poll_fun
= asyncore
.poll3
45 poll_fun
= asyncore
.poll2
47 poll_fun
= asyncore
.poll
51 while tasks
and tasks
[0].time
< now
:
52 task
= heapq
.heappop(tasks
)
57 t
= max(min(t
, tasks
[0].time
- now
), 0)
61 signal
.signal(signal
.SIGTERM
, oldhandler
)
67 __all__
= ("schedule", "loop", "exit")