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

时间:2017-05-29 12:16:31

标签: python python-2.7 timer python-multithreading



 
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秒将此数据发送到服务器。我试图使用一个线程,但它不起作用。

任何人都可以告诉我这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

要定期运行某些代码(固定时间间隔),您可以使用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()))

更大的列表:

def sendDataToServer(temperature, humidity, pressure):
    urllib.urlopen(
        "http://www.teema.club/projectweather/add_data.php?"
        "temp=%.1f&hum=%.1f&pr=%.1f" % (
            temperature, humidity, pressure)
    ).read()


import time
next_time = time.time()
while True:
    # Read data
    temperature = humidity = pressure = 1.0

    # Send data
    sendDataToServer(temperature, humidity, pressure)

    next_time += 5
    time.sleep(max(0, next_time - time.time()))