Andrei Buruntia
Andrei Buruntia

Reputation: 113

Threaded HTTP post via requests without waiting for request to go through

My program is sending out an http post every 250ms or so and I want it to keep running while the request goes through. Essentially I am looking for something like a file and forget system that just sends off the request (perhaps in a different thread) and keeps on going without waiting for a response from the server.

The program looks something like:

while True:
    value_to_send = some_function()
    x = requests.post(url, json = myjson) # this json has the updated value_to_send in it 

Upvotes: 0

Views: 522

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18136

You could use threads and simply dont wait for them to finish:

from threading import Thread
import time

def request():
    # value_to_send = some_function()
    # x = requests.post(url, json = myjson)
    print('started')
    time.sleep(.5)
    print("request done!")


def main():
    while True:
        t = Thread(target=request)
        t.start()
        time.sleep(.25)

main()

Output:

started
started
request done!
started
request done!
started
request done!
...

Upvotes: 1

Related Questions