python version of settimout

Solutions on MaxInterview for python version of settimout by the best coders in the world

showing results for - "python version of settimout"
Sofia
25 Jan 2017
1from datetime import datetime, timedelta
2import heapq
3
4# just holds a function, its arguments, and when we want it to execute.
5class TimeoutFunction:
6    def __init__(self, function, timeout, *args):
7        self.function = function
8        self.args = args
9        self.startTime = datetime.now() + timedelta(0,0,0,timeout) 
10
11    def execute(self):
12        self.function(*self.args)
13
14# A "todo" list for all the TimeoutFunctions we want to execute in the future
15# They are sorted in the order they should be executed, thanks to heapq
16class TodoList: 
17    def __init__(self):
18        self.todo = []
19
20    def addToList(self, tFunction):
21        heapq.heappush(self.todo, (tFunction.startTime, tFunction))
22
23    def executeReadyFunctions(self):
24        if len(self.todo) > 0:
25            tFunction = heapq.heappop(self.todo)[1]
26            while tFunction and datetime.now() > tFunction.startTime:
27                #execute all the functions that are ready
28                tFunction.execute()
29                if len(self.todo) > 0:
30                    tFunction = heapq.heappop(self.todo)[1]
31                else:
32                    tFunction = None                    
33            if tFunction:
34                #this one's not ready yet, push it back on
35                heapq.heappush(self.todo, (tFunction.startTime, tFunction))
36
37def singleArgFunction(x):
38    print str(x)
39
40def multiArgFunction(x, y):
41    #Demonstration of passing multiple-argument functions
42    print str(x*y)
43
44# Make some TimeoutFunction objects
45# timeout is in milliseconds
46a = TimeoutFunction(singleArgFunction, 1000, 20)
47b = TimeoutFunction(multiArgFunction, 2000, *(11,12))
48c = TimeoutFunction(quit, 3000, None)
49
50todoList = TodoList()
51todoList.addToList(a)
52todoList.addToList(b)
53todoList.addToList(c)
54
55while True:
56    todoList.executeReadyFunctions()