[英]Python periodic task inside an infinite loop
I need to execute a piece of code inside a while True
loop every, let's say, 5 seconds. 我需要每隔5秒
while True
循环中执行一段代码。 I know the threading.Timer(5, foo).start()
will be run every 5 seconds but my foo()
function depends on a variable inside my while
loop. 我知道
threading.Timer(5, foo).start()
将每5秒运行一次,但是我的foo()
函数取决于while
循环中的变量。
The foo
is actually run on another thread and I don't want to block the current thread just for timing's sake. foo
实际上是在另一个线程上运行的,我不想为了计时而阻塞当前线程。
+------------------------while #main-thread---------------------------------
|
+..........foo(val)..........foo(val)...........foo(val)............foo(val)
-5s- -5s- -5s- -5s-
Something like this: 像这样:
def input(self):
vals = []
while True:
# fill the vals
# run `foo(vals)` every 5 seconds
def foo(vals):
print vals
Is there any Pythonic way of doing this? 有没有Pythonic的方法可以做到这一点?
Use the sleep
function: 使用
sleep
功能:
import time
def input(self):
vals = []
while True:
# fill the vals
foo(vals)
time.sleep(5)
def foo(vals):
print vals
Note that the command will run every 5 seconds exactly only if the time needed to run it is itself negligible. 请注意,只有在运行所需的时间本身可以忽略的情况下,该命令才每5秒准确运行一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.