Python periodic task inside an infinite loop

人走茶凉 提交于 2019-12-25 11:45:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!