本文介绍了有没有办法阻止计时器蠕变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种每秒运行一个方法的方法,无论运行需要多长时间.在寻求帮助时,我遇到了

I am looking for a way to run a method every second, regardless of how long it takes to run. In looking for help with that, I ran across

每 n 秒运行一次特定代码

并在尝试时发现它无法正常工作.它似乎有我试图避免的问题:漂移.我尝试在打印后添加一个sleep(0.5)",它实际上减慢了循环速度,并且间隔保持在 1.003(大约)秒.

and in trying it, found that it doesn't work correctly. It appears to have the very problem I'm trying to avoid: drift. I tried adding a "sleep(0.5)" after the print, and it does in fact slow down the loop, and the interval stays at the 1.003 (roughly) seconds.

有没有办法解决这个问题,做我想做的事?

Is there a way to fix this, to do what I want?

(venv) 20170728-153445 mpeck@bilbo:~/dev/whiskerlabs/aphid/loadtest$ cat a.py
import threading
import time
def woof():
  threading.Timer(1.0, woof).start()
  print "Hello at %s" % time.time()
woof()
(venv) 20170728-153449 mpeck@bilbo:~/dev/whiskerlabs/aphid/loadtest$ python a.py
Hello at 1501281291.84
Hello at 1501281292.85
Hello at 1501281293.85
Hello at 1501281294.85
Hello at 1501281295.86
Hello at 1501281296.86
Hello at 1501281297.86
Hello at 1501281298.87
Hello at 1501281299.87
Hello at 1501281300.88
Hello at 1501281301.88
Hello at 1501281302.89
Hello at 1501281303.89
Hello at 1501281304.89
Hello at 1501281305.89
Hello at 1501281306.9
Hello at 1501281307.9
Hello at 1501281308.9
Hello at 1501281309.91
Hello at 1501281310.91
Hello at 1501281311.91
Hello at 1501281312.91
Hello at 1501281313.92
Hello at 1501281314.92
Hello at 1501281315.92
Hello at 1501281316.93

推荐答案

  1. 如果您实际上不需要每次都创建一个新线程,请不要使用 threading.Timer;在循环中定期运行一个函数 sleep 就可以了(可能在一个单独的线程中).

  1. Don't use a threading.Timer if you don't actually need a new thread each time; to run a function periodically sleep in a loop will do (possibly in a single separate thread).

无论您使用什么方法来安排下一次执行,都不要等待您用作间隔的确切时间量 - 其他语句的执行需要时间,因此结果是如您所见的漂移.相反,在变量中记下初始时间,并在每次迭代时计算您想要安排执行和睡眠的下一次时间,以了解现在和那时之间的差异.

Whatever method you use to schedule the next execution, don't wait for the exact amount of time you use as interval - execution of the other statements take time, so the result is drift as you can see. Instead, write down the initial time in a variable, and at each iteration calculate the next time when you want to schedule execution and sleep for the difference between now and then.

interval = 1.
next_t = time.time()
while True:
    next_t += interval
    time.sleep(next_t - time.time())
    # do whatever you want to do

(当然你可以改进它以获得更好的整体准确性,但这至少应该避免漂移)

(of course you may refine it for better overall accuracy, but this at least should avoid drift)

这篇关于有没有办法阻止计时器蠕变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 18:22