Python无限循环内的周期性任务

时间:2014-09-21 09:30:17

标签: python python-2.7 scheduled-tasks timer-jobs

我需要在while True循环内执行一段代码,比如5秒钟。我知道threading.Timer(5, foo).start()将每5秒运行一次,但我的foo()函数取决于while循环内的变量。

foo实际上是在另一个线程上运行的,我不想仅仅为了时间而阻止当前线程。

+------------------------while #main-thread---------------------------------
|
+..........foo(val)..........foo(val)...........foo(val)............foo(val)
    -5s-              -5s-               -5s-               -5s- 

这样的事情:

def input(self):
      vals = []
      while True:
           # fill the vals
           # run `foo(vals)` every 5 seconds

def foo(vals):
    print vals

有没有Pythonic这样做的方法?

1 个答案:

答案 0 :(得分:2)

使用sleep功能:

import time
def input(self):
      vals = []
      while True:
           # fill the vals
           foo(vals)
           time.sleep(5)

def foo(vals):
    print vals

请注意,只有运行它所需的时间本身可以忽略不计,该命令才会每5秒运行一次。