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秒将此数据发送到服务器。我试图使用一个线程,但它不起作用。
任何人都可以告诉我这是正确的方法吗?
答案 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()))