每N秒定期在线程中实时执行功能 [英] Periodically execute function in thread in real time, every N seconds

查看:78
本文介绍了每N秒定期在线程中实时执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程化的类,它的循环每秒需要执行4次.我知道我可以做类似的事情

I have a threaded class whose loop needs to execute 4 times every second. I know that I can do something like

do_stuff()
time.sleep(0.25)

,但是问题在于这并不能说明do_stuff()所花费的时间.实际上,这需要是一个实时线程.有没有办法做到这一点?理想情况下,当不执行代码时,线程仍将处于休眠状态.

but the problem is that is doesn't account for the time it takes to do_stuff(). Effectively this needs to be a real-time thread. Is there a way to accomplish this? Ideally the thread would still be put to sleep when not executing code.

推荐答案

简单的解决方案

import threading

def work (): 
  threading.Timer(0.25, work).start ()
  print "stackoverflow"

work ()


以上内容可确保work以每秒四次的间隔运行,其背后的理论是它将"queue" 对其自身的调用将被运行 0.25 秒,而无需等待它发生.


The above will make sure that work is run with an interval of four times per second, the theory behind this is that it will "queue" a call to itself that will be run 0.25 seconds into the future, without hanging around waiting for that to happen.

因此,它几乎可以不间断地完成工作,并且我们非常接近每秒精确执行4次该功能.

Because of this it can do it's work (almost) entirely uninterrupted, and we are extremely close to executing the function exactly 4 times per second.

有关threading.Timer的更多信息,可以通过以下指向python文档的链接进行阅读:

More about threading.Timer can be read by following the below link to the python documentation:

即使先前的功能按预期工作,您也可以创建一个辅助函数来协助处理将来的定时事件.

Even though the previous function works as expected you could create a helper function to aid in dealing with future timed events.

对于本示例,以下内容就足够了,希望代码能说明一切-它并不像看起来的那样先进.

Something as the below will be sufficient for this example, hopefully the code will speak for itself - it is not as advanced as it might appear.

当您可以实现自己的包装程序以适合您的确切需求时,将此视为启发.

See this as an inspiration when you might implement your own wrapper to fit your exact needs.

import threading

def do_every (interval, worker_func, iterations = 0):
  if iterations != 1:
    threading.Timer (
      interval,
      do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1]
    ).start ()

  worker_func ()

def print_hw ():
  print "hello world"

def print_so ():
  print "stackoverflow"


# call print_so every second, 5 times total
do_every (1, print_so, 5)

# call print_hw two times per second, forever
do_every (0.5, print_hw)

这篇关于每N秒定期在线程中实时执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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