无限循环内的Python周期性任务 [英] Python periodic task inside an infinite loop

查看:69
本文介绍了无限循环内的Python周期性任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 while True 循环中每隔 5 秒执行一段代码.我知道 threading.Timer(5, foo).start() 将每 5 秒运行一次,但我的 foo() 函数依赖于我的 中的一个变量while 循环.

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.

foo 实际上是在另一个线程上运行的,我不想为了计时而阻塞当前线程.

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- 

像这样:

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

def foo(vals):
    print vals

有没有 Pythonic 的方法来做到这一点?

Is there any Pythonic way of doing this?

推荐答案

使用 sleep 函数:

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

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

Note that the command will run every 5 seconds exactly only if the time needed to run it is itself negligible.

这篇关于无限循环内的Python周期性任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆