blob: b2fbe76563827e6d452780bfa8d157106b68dfb9 [file] [log] [blame]
Guido van Rossum2d844d11991-04-07 13:41:50 +00001# Combine a real-time scheduling queue and stdwin event handling.
Guido van Rossumb6775db1994-08-01 11:34:53 +00002# Keeps times in milliseconds.
Guido van Rossum2d844d11991-04-07 13:41:50 +00003
Guido van Rossum0d3f4671991-08-16 13:22:53 +00004import stdwin, stdwinq
Guido van Rossum2d844d11991-04-07 13:41:50 +00005from stdwinevents import WE_TIMER
Guido van Rossum0d3f4671991-08-16 13:22:53 +00006import mainloop
Guido van Rossum2d844d11991-04-07 13:41:50 +00007import sched
8import time
9
10# Delay function called by the scheduler when it has nothing to do.
11# Return immediately when something is done, or when the delay is up.
12#
13def delayfunc(msecs):
14 #
15 # Check for immediate stdwin event
16 #
Guido van Rossum0d3f4671991-08-16 13:22:53 +000017 event = stdwinq.pollevent()
Guido van Rossum2d844d11991-04-07 13:41:50 +000018 if event:
Guido van Rossum0d3f4671991-08-16 13:22:53 +000019 mainloop.dispatch(event)
Guido van Rossum2d844d11991-04-07 13:41:50 +000020 return
21 #
Guido van Rossumb6775db1994-08-01 11:34:53 +000022 # Use sleep for very short delays or if there are no windows
Guido van Rossum2d844d11991-04-07 13:41:50 +000023 #
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000024 if msecs < 100 or mainloop.countwindows() == 0:
Guido van Rossum001fa6a1991-04-21 19:31:10 +000025 if msecs > 0:
Guido van Rossumb6775db1994-08-01 11:34:53 +000026 time.sleep(msecs * 0.001)
Guido van Rossum2d844d11991-04-07 13:41:50 +000027 return
28 #
29 # Post a timer event on an arbitrary window and wait for it
30 #
Guido van Rossum0d3f4671991-08-16 13:22:53 +000031 window = mainloop.anywindow()
Guido van Rossum2d844d11991-04-07 13:41:50 +000032 window.settimer(msecs/100)
Guido van Rossum0d3f4671991-08-16 13:22:53 +000033 event = stdwinq.getevent()
Guido van Rossum2d844d11991-04-07 13:41:50 +000034 window.settimer(0)
35 if event[0] <> WE_TIMER:
Guido van Rossum0d3f4671991-08-16 13:22:53 +000036 mainloop.dispatch(event)
Guido van Rossum2d844d11991-04-07 13:41:50 +000037
Guido van Rossumb6775db1994-08-01 11:34:53 +000038def millitimer():
39 return int(1000 * time.time())
40
41q = sched.scheduler(millitimer, delayfunc)
Guido van Rossum2d844d11991-04-07 13:41:50 +000042
43# Export functions enter, enterabs and cancel just like a scheduler
44#
45enter = q.enter
46enterabs = q.enterabs
47cancel = q.cancel
48
49# Emptiness check must check both queues
50#
51def empty():
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000052 return q.empty() and mainloop.countwindows() == 0
Guido van Rossum2d844d11991-04-07 13:41:50 +000053
54# Run until there is nothing left to do
55#
56def run():
57 while not empty():
58 if q.empty():
Guido van Rossum0d3f4671991-08-16 13:22:53 +000059 mainloop.dispatch(stdwinq.getevent())
Guido van Rossum2d844d11991-04-07 13:41:50 +000060 else:
61 q.run()