1

 
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()
 

This is my Python code which sends some values to a server using a url with some parameters. I need to send this data to server after every 5 seconds. I tried to use a thread but it does not work.

Can anyone tell me is it proper way to do this?

1 Answer 1

1

To run some code on a regular schedule (fixed time interval) you can use time.sleep() like:

Code:

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()))

Larger listing:

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()))
Sign up to request clarification or add additional context in comments.

3 Comments

this will halt my program for certain seconds. What if I want my other functions to be in a running state at that moment. Apart from multithreading is there some another way how i can achieve this?
@Ishanmahajan, There are myriad ways to do this.
can you please list out some of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.