如何在Python中运行特定时间的函数?
比如说,我有一个函数叫做 do_something()
,我希望它能准确运行1秒钟(不能是0.923秒,这样不行。不过0.999秒是可以接受的)。
但是,确保 do_something
准确运行1秒钟是非常非常重要的。我在考虑使用UNIX时间戳来计算秒数。但我真的想知道Python有没有更简单好看的方法来做到这一点……
这个函数 do_something()
运行时间比较长,必须在准确1秒后被中断。
3 个回答
1
Python的'sched'模块看起来很合适:
http://docs.python.org/library/sched.html
另外,Python并不是一种实时语言,也通常不在实时操作系统上运行。所以你的需求有点值得怀疑。
2
我从评论中了解到,这里有一个while
循环。下面是一个类,它继承自Thread
,这个类的代码是基于threading
模块中_Timer
的源代码。我知道你说过你不想用线程,但这个只是一个定时器控制线程;do_something
是在主线程中执行的。所以这个应该是干净的。如果我说错了,请有人纠正我!
from threading import Thread, Event
class BoolTimer(Thread):
"""A boolean value that toggles after a specified number of seconds:
bt = BoolTimer(30.0, False)
bt.start()
bt.cancel() # prevent the booltimer from toggling if it is still waiting
"""
def __init__(self, interval, initial_state=True):
Thread.__init__(self)
self.interval = interval
self.state = initial_state
self.finished = Event()
def __nonzero__(self):
return bool(self.state)
def cancel(self):
"""Stop BoolTimer if it hasn't toggled yet"""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.state = not self.state
self.finished.set()
你可以这样使用它。
import time
def do_something():
running = BoolTimer(1.0)
running.start()
while running:
print "running" # Do something more useful here.
time.sleep(0.05) # Do it more or less often.
if not running: # If you want to interrupt the loop,
print "broke!" # add breakpoints.
break # You could even put this in a
time.sleep(0.05) # try, finally block.
do_something()
0