-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsimSched.py
64 lines (48 loc) · 1.84 KB
/
simSched.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import heapq, uuid
# A quick UUID lambda to get a hex string uuid
newUUID = lambda: uuid.uuid4().hex
class OperationSched(object):
'''This is a class designed to run simulated events,
each of which may or may not schedule additional event(s)
in the future.'''
def __init__(self):
self.time = 0
self.events = {}
self.schedule = []
def passTime(self, deltaTime):
assert deltaTime >= 0, "No Time Travel Please!"
self.time += deltaTime
def whatTime(self):
return self.time
def enter(self, deltaTime, functionToCall, args=tuple(), kwargs=dict()):
# Make a uuid for this event
idee = newUUID()
# Archive the function, args and kwargs
self.events[idee] = (functionToCall, args, kwargs)
# Enter the UUID in the heap
eventTuple = (self.whatTime() + deltaTime, idee)
heapq.heappush(self.schedule, eventTuple)
return idee
def runEvent(self):
# Execute a single event
eventTime, eventID = heapq.heappop(self.schedule)
functionToCall, args, kwargs = self.events.pop(eventID)
functionToCall(*args, **kwargs)
def getNextEventTime(self):
return self.schedule[0][0]
def run(self, maxTime=float("inf"), maxEventCount=float("inf")):
eventsRun = 0
timePassed = 0
# Actual Run Loop
while (timePassed < maxTime) and (eventsRun < maxEventCount):
# Give up if we run out of events
if len(self.schedule) == 0:
break
# Move time forward as necessary
theFuture = self.getNextEventTime() - self.whatTime()
self.passTime(theFuture)
# Run the event
self.runEvent()
# Update our semaphores for completion
eventsRun += 1
timePassed += theFuture