在实践中,计时器可能是您要做的最简单的方法。
此代码将执行以下 *** 作:
- 1秒后,它会显示“ arg1 arg2”
- 2秒后,它会显示“ OWLS OWLS OWLS”
===
from threading import Timerdef twoArgs(arg1,arg2): print arg1 print arg2 print ""def nArgs(*args): for each in args: print each#arguments: #how long to wait (in seconds), #what function to call, #what gets passed inr = Timer(1.0, twoArgs, ("arg1","arg2"))s = Timer(2.0, nArgs, ("OWLS","OWLS","OWLS"))r.start()s.start()
===
上面的代码很可能会解决您的问题。
但!还有另一种方法,不使用多线程。它的工作方式更像单线程的Javascript。
对于此单线程版本,您需要做的就是将函数及其参数存储在一个对象中,以及应该运行该函数的时间。
一旦有了包含函数调用和超时的对象,只需定期检查函数是否准备就绪即可执行。
正确的方法是使优先级队列存储我们将来要运行的所有功能,如下面的代码所示。
就像在Javascript中一样,这种方法不能保证该函数将完全按时运行。运行时间很长的功能将延迟其后的功能。但是,它确实保证了函数将 不早
于其超时运行。
此代码将执行以下 *** 作:
- 1秒后,它会显示“ 20”
- 2秒后,它会显示“ 132”
- 3秒后,它退出。
===
from datetime import datetime, timedeltaimport heapq# just holds a function, its arguments, and when we want it to execute.class TimeoutFunction: def __init__(self, function, timeout, *args): self.function = function self.args = args self.startTime = datetime.now() + timedelta(0,0,0,timeout) def execute(self): self.function(*self.args)# A "todo" list for all the TimeoutFunctions we want to execute in the future# They are sorted in the order they should be executed, thanks to heapqclass TodoList: def __init__(self): self.todo = [] def addToList(self, tFunction): heapq.heappush(self.todo, (tFunction.startTime, tFunction)) def executeReadyFunctions(self): if len(self.todo) > 0: tFunction = heapq.heappop(self.todo)[1] while tFunction and datetime.now() > tFunction.startTime: #execute all the functions that are ready tFunction.execute() if len(self.todo) > 0: tFunction = heapq.heappop(self.todo)[1] else: tFunction = None if tFunction: #this one's not ready yet, push it back on heapq.heappush(self.todo, (tFunction.startTime, tFunction))def singleArgFunction(x): print str(x)def multiArgFunction(x, y): #Demonstration of passing multiple-argument functions print str(x*y)# Make some TimeoutFunction objects# timeout is in millisecondsa = TimeoutFunction(singleArgFunction, 1000, 20)b = TimeoutFunction(multiArgFunction, 2000, *(11,12))c = TimeoutFunction(quit, 3000, None)todoList = TodoList()todoList.addToList(a)todoList.addToList(b)todoList.addToList(c)while True: todoList.executeReadyFunctions()
===
在实践中,您可能会在while循环中进行更多 *** 作,而不仅仅是检查超时功能是否准备就绪。您可能正在轮询用户输入,控制某些硬件,读取数据等。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)