]>
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 __lt__(self
, other
):
19 return self
.time
< other
.time
21 def __eq__(self
, other
):
22 return self
.time
== other
.time
31 assert self
.func
is not None
34 def schedule(delay
, func
, args
=[], kwargs
={}):
35 task
= Task(delay
, func
, args
, kwargs
)
36 heapq
.heappush(tasks
, task
)
39 def loop(timeout
=30.0, use_poll
=False):
42 oldhandler
= signal
.signal(signal
.SIGTERM
, exit
)
45 if hasattr(select
, 'poll'):
46 poll_fun
= asyncore
.poll3
48 poll_fun
= asyncore
.poll2
50 poll_fun
= asyncore
.poll
54 while tasks
and tasks
[0].time
< now
:
55 task
= heapq
.heappop(tasks
)
60 t
= max(min(t
, tasks
[0].time
- now
), 0)
64 signal
.signal(signal
.SIGTERM
, oldhandler
)
70 __all__
= ("schedule", "loop", "exit")