您的位置:首页技术文章
文章详情页

将代码推迟以供以后在python中执行(例如javascript中的setTimeout)。

【字号: 日期:2022-08-07 14:15:06浏览:4作者:猪猪
如何解决将代码推迟以供以后在python中执行(例如javascript中的setTimeout)。?

在实践中,计时器可能是您要做的最简单的方法。

此代码将执行以下操作:

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 = functionself.args = argsself.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 readytFunction.execute()if len(self.todo) > 0: tFunction = heapq.heappop(self.todo)[1]else: tFunction = Noneif tFunction:#this one’s not ready yet, push it back onheapq.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循环中进行更多操作,而不仅仅是检查超时功能是否准备就绪。您可能正在轮询用户输入,控制某些硬件,读取数据等。

解决方法

我必须在python中执行一个程序,该程序需要执行一段时间,然后(无论在何处执行)它必须将信息转储到文件中,关闭文件,然后退出。

在JavaScript中,此行为等同于使用setTimeout(func,1000000)其第一个参数(func)将是具有退出代码的函数的指针,而其第二个参数将是程序可用的时间的用法。

我知道如何用C制作这个程序(使用SO信号),但是使用python

标签: Python 编程
相关文章: