drdot
drdot

Reputation: 3347

Python: Periodically run http requests in thread

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?

Upvotes: 0

Views: 562

Answers (1)

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9704

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)

Upvotes: 1

Related Questions