2

I'd like a function to be performed at a set rate, say, 6 times a second. What it is the best way to go about this with Python?

I tried a simple time.sleep() thing at the end of my loop, but that, of course, acts nothing like a reliable clock. Any change in CPU usage, and suddenly the "timer" has drifted quite far from where it started.

4

2 回答 2

2

试试celery。例子:

from celery.task import tasks, PeriodicTask
from datetime import timedelta

class Every100MillisecondsTask(PeriodicTask):
    run_every = timedelta(milliseconds=100)

    def run(self, **kwargs):
        logger = self.get_logger(**kwargs)
        logger.info("Execute 10 times per second")

未经测试,但应该可以工作。您可以更改这些值以获得所需的分辨率。您甚至可以以微秒为单位传递 timedelta。实际上改编自这个答案

于 2012-12-26T17:39:04.293 回答
0

像这样的东西应该工作。它不会漂移,因为它固定在固定的开始时间。

import time

def repeat(func, interval):
    start = time.time()
    tick = interval / 50.0
    count = 0
    while True:
        if time.time() >= start + interval * count:
            func()
            count += 1
        time.sleep(tick)

如果您想foo每秒运行六次函数,请执行以下操作:

def foo(): 
    print '.',

repeat(foo, 1.0 / 6)

编辑: 我喜欢 mccrustin 使用 celery 的答案,但如果你需要自己动手,这个答案应该可以。

于 2012-12-26T17:50:52.023 回答