python - 以精确的时间间隔循环 [英] python - loop at exact time intervals

查看:51
本文介绍了python - 以精确的时间间隔循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to run a piece of code at exact time intervals (of the order of 15 seconds) Initially I used time.sleep(), but then the problem is the code takes a second or so to run, so it will get out of sync.

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

I wrote this, which I feel is untidy because I don't like using while loops. Is there a better way?

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

推荐答案

理想情况下,可以使用线程来完成此任务.你可以做类似的事情

Ideally one would use threading to accomplish this. You can do something like

import threading
interval = 15

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

def startTimer():
    threading.Timer(interval, startTimer).start()
    myPeriodicFunction()

然后你就可以打电话

startTimer()

为了启动循环计时器.

这篇关于python - 以精确的时间间隔循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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