0
import requests
import json
import threading

data = {
  "amount": 2
}


def foo(data):
    try:
        r = requests.post(url = "www.mysite.com", data = data)
        j = json.loads(r.text)
        print(j)
    except requests.exceptions.RequestException as e:
        raise SystemExist(e)


threading.Timer(1, foo, [data]).start()

I want to run this http request every second using a thread in my program. However, the program only runs the http request once and exit. How do I fix this?

ppwater
  • 2,315
  • 4
  • 15
  • 29
drdot
  • 3,215
  • 9
  • 46
  • 81
  • 1
    `Timer` objects only run once after a given number of seconds. See [Python threading.timer - repeat function every 'n' seconds](https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds) – Selcuk Nov 04 '20 at 07:46
  • or you can create infinite `while`-loop inside thread instead of using `Timer` – Vladimir Nov 04 '20 at 11:58

1 Answers1

1

You need to restart the timer after each request :

def foo(data):
    try:
        r = requests.post(url = "www.mysite.com", data = data)
        j = json.loads(r.text)
        print(j)
        threading.Timer(1, foo, [data]).start() # New Line Added
    except requests.exceptions.RequestException as e:
        raise SystemExist(e)
Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33
  • Thank you. The approach looks differently from the link suggested by some people https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds . Could you elaborate the pros and cons? – drdot Nov 04 '20 at 16:55
  • Personally I don't like wait loops unless i need to use them, but the best thing to do if you are concerned is to measure any differences. – Tony Suffolk 66 Nov 07 '20 at 00:42
  • What kind of differences? – drdot Nov 07 '20 at 05:49
  • There might be performance differences depending on your system loading, and other loading conditions in your applications - it might affect overall throughput etc, CPU usage etc. – Tony Suffolk 66 Nov 07 '20 at 19:28