python - 以精确的时间间隔循环

And*_*ore 4 time python-3.x

我想以精确的时间间隔(大约 15 秒)运行一段代码最初我使用 time.sleep(),但问题是代码需要一秒钟左右才能运行,所以它会退出同步。

我写了这个,我觉得它不整洁,因为我不喜欢使用 while 循环。有没有更好的办法?

import datetime as dt
import numpy as np

iterations = 100
tstep = dt.timedelta(seconds=5)
for i in np.arange(iterations):
    startTime = dt.datetime.now()
    myfunction(doesloadsofcoolthings)
    while dt.datetime.now() < startTime + tstep:
        1==1
Run Code Online (Sandbox Code Playgroud)

Jon*_*ton 8

理想情况下,人们会使用线程来实现这一点。你可以做类似的事情

import threading
interval = 15

def myPeriodicFunction():
    print "This loops on a timer every %d seconds" % interval

def startTimer():
    threading.Timer(interval, startTimer).start()
    myPeriodicFunction()
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话

startTimer()
Run Code Online (Sandbox Code Playgroud)

以启动循环计时器。