Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何在特定的时间间隔后运行方法?_Python_Python 2.7_Timer_Python Multithreading - Fatal编程技术网

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

在Python中,如何在特定的时间间隔后运行方法?,python,python-2.7,timer,python-multithreading,Python,Python 2.7,Timer,Python Multithreading,def sendDataToServer(): 全球温度 Timer(5.0,sendDataToServer).start() 打印(“感测…”) readSensor() ReadCputTemperature() 温度=圆形(温度,1) 打印(温度) 打印(湿度) 打印(压力) 温度=“.1f%”温度 hum=“.1f%”湿度 按=“.1f%”压力 urllib.urlopen(“http://www.teema.club/projectweather/add_data.php?temp=


def sendDataToServer():
全球温度
Timer(5.0,sendDataToServer).start()
打印(“感测…”)
readSensor()
ReadCputTemperature()
温度=圆形(温度,1)
打印(温度)
打印(湿度)
打印(压力)
温度=“.1f%”温度
hum=“.1f%”湿度
按=“.1f%”压力
urllib.urlopen(“http://www.teema.club/projectweather/add_data.php?temp=“+temp+”&hum=“+hum+”&pr=“+按)。读取()
sendDataToServer()

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

代码: 更大的列表:
这将使我的程序停止若干秒。如果我希望我的其他函数此时处于运行状态,该怎么办。除了多线程之外,还有其他方法吗?@Ishanmahajan,有很多方法可以做到这一点。你能列出一些方法吗。
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()))