26
26
import time
27
27
import heapq
28
28
from collections import namedtuple
29
+ from itertools import count
29
30
import threading
30
31
from time import monotonic as _time
31
32
32
33
__all__ = ["scheduler" ]
33
34
34
- class Event (namedtuple ('Event' , 'time, priority, action, argument, kwargs' )):
35
- __slots__ = []
36
- def __eq__ (s , o ): return (s .time , s .priority ) == (o .time , o .priority )
37
- def __lt__ (s , o ): return (s .time , s .priority ) < (o .time , o .priority )
38
- def __le__ (s , o ): return (s .time , s .priority ) <= (o .time , o .priority )
39
- def __gt__ (s , o ): return (s .time , s .priority ) > (o .time , o .priority )
40
- def __ge__ (s , o ): return (s .time , s .priority ) >= (o .time , o .priority )
41
-
35
+ Event = namedtuple ('Event' , 'time, priority, sequence, action, argument, kwargs' )
42
36
Event .time .__doc__ = ('''Numeric type compatible with the return value of the
43
37
timefunc function passed to the constructor.''' )
44
38
Event .priority .__doc__ = ('''Events scheduled for the same time will be executed
45
39
in the order of their priority.''' )
40
+ Event .sequence .__doc__ = ('''A continually increasing sequence number that
41
+ separates events if time and priority are equal.''' )
46
42
Event .action .__doc__ = ('''Executing the event means executing
47
43
action(*argument, **kwargs)''' )
48
44
Event .argument .__doc__ = ('''argument is a sequence holding the positional
@@ -61,6 +57,7 @@ def __init__(self, timefunc=_time, delayfunc=time.sleep):
61
57
self ._lock = threading .RLock ()
62
58
self .timefunc = timefunc
63
59
self .delayfunc = delayfunc
60
+ self ._sequence_generator = count ()
64
61
65
62
def enterabs (self , time , priority , action , argument = (), kwargs = _sentinel ):
66
63
"""Enter a new event in the queue at an absolute time.
@@ -71,8 +68,10 @@ def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
71
68
"""
72
69
if kwargs is _sentinel :
73
70
kwargs = {}
74
- event = Event ( time , priority , action , argument , kwargs )
71
+
75
72
with self ._lock :
73
+ event = Event (time , priority , next (self ._sequence_generator ),
74
+ action , argument , kwargs )
76
75
heapq .heappush (self ._queue , event )
77
76
return event # The ID
78
77
@@ -136,7 +135,8 @@ def run(self, blocking=True):
136
135
with lock :
137
136
if not q :
138
137
break
139
- time , priority , action , argument , kwargs = q [0 ]
138
+ (time , priority , sequence , action ,
139
+ argument , kwargs ) = q [0 ]
140
140
now = timefunc ()
141
141
if time > now :
142
142
delay = True
0 commit comments