问题
I need to execute a piece of code inside a while True
loop every, let's say, 5 seconds. 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.
The foo
is actually run on another thread and I don't want to block the current thread just for timing's sake.
+------------------------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?
回答1:
Use the sleep function:
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.
来源:https://stackoverflow.com/questions/25957782/python-periodic-task-inside-an-infinite-loop