在Python中如何在特定的时间间隔后运行方法?

2024-10-02 22:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

def sendDataToServer(): global temperature threading.Timer(5.0, sendDataToServer).start() print("Sensing...") readSensor() readCPUTemperature() temperature = round(temperature, 1) print(temperature) print(humidity) print(pressure) temp = "%.1f" % temperature hum = "%.1f" % humidity press = "%.1f" % pressure urllib.urlopen("http://www.teema.club/projectweather/add_data.php?temp=" + temp + "&hum=" + hum + "&pr=" + press).read() sendDataToServer()

这是我的Python代码,它使用带有一些参数的url向服务器发送一些值。我需要每隔5秒把这些数据发送到服务器。我试着用一根线,但没用。在

有谁能告诉我这是正确的方法吗?在


Tags: defglobalstarttemppressprintthreadingtimer
1条回答
网友
1楼 · 发布于 2024-10-02 22:26:51

要按常规计划(固定时间间隔)运行某些代码,可以使用time.sleep(),如:

代码:

next_time = time.time()
while True:   
    # do some work here
    ....

    # wait for next interval
    next_time += 5
    time.sleep(max(0, next_time - time.time()))

大型上市公司:

^{pr2}$

相关问题 更多 >