python version of settimout April 13, 2023 by wordlinkanswers python version of settimout Comment 0 from datetime import datetime, timedelta<br /> import heapq</p> <p># just holds a function, its arguments, and when we want it to execute.<br /> class TimeoutFunction:<br /> def __init__(self, function, timeout, *args):<br /> self.function = function<br /> self.args = args<br /> self.startTime = datetime.now() + timedelta(0,0,0,timeout) </p> <p> def execute(self):<br /> self.function(*self.args)</p> <p># A “todo” list for all the TimeoutFunctions we want to execute in the future<br /> # They are sorted in the order they should be executed, thanks to heapq<br /> class TodoList:<br /> def __init__(self):<br /> self.todo = []</p> <p> def addToList(self, tFunction):<br /> heapq.heappush(self.todo, (tFunction.startTime, tFunction))</p> <p> def executeReadyFunctions(self):<br /> if len(self.todo) > 0:<br /> tFunction = heapq.heappop(self.todo)[1]<br /> while tFunction and datetime.now() > tFunction.startTime:<br /> #execute all the functions that are ready<br /> tFunction.execute()<br /> if len(self.todo) > 0:<br /> tFunction = heapq.heappop(self.todo)[1]<br /> else:<br /> tFunction = None<br /> if tFunction:<br /> #this one’s not ready yet, push it back on<br /> heapq.heappush(self.todo, (tFunction.startTime, tFunction))</p> <p>def singleArgFunction(x):<br /> print str(x)</p> <p>def multiArgFunction(x, y):<br /> #Demonstration of passing multiple-argument functions<br /> print str(x*y)</p> <p># Make some TimeoutFunction objects<br /> # timeout is in milliseconds<br /> a = TimeoutFunction(singleArgFunction, 1000, 20)<br /> b = TimeoutFunction(multiArgFunction, 2000, *(11,12))<br /> c = TimeoutFunction(quit, 3000, None)</p> <p>todoList = TodoList()<br /> todoList.addToList(a)<br /> todoList.addToList(b)<br /> todoList.addToList(c)</p> <p>while True:<br /> todoList.executeReadyFunctions() Popularity 7/10 Helpfulness 2/10 Language python Source: stackoverflow.com Tags: python version Share Link to this answer Share Contributed on Feb 28 2020 webdevjaz 0 Answers Avg Quality 2/10 wordlinkanswers