Python : How to run a function "foo" per second and last a few minutes or hours

Scenario

I tried to run a function "foo" every second. I have to do this for a few minutes (say 5).

The function foo () sends 100 HTTP requests (including JSON objects) to the server and prints the JSON response.

In short, I have to issue 100 HTTP requests per second for 5 minutes.

Using threading.Timer

#!/usr/bin/python
import time
import thread
import threading

def foo():
    print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), threading.active_count()

#5 minutes = 5 * 60 = 300 seconds
for x in range(0, 300):
    t = threading.Timer(x + 1, foo)
    t.start()

Expected output

function foo was executed per second and last about 5 minutes

2020-05-14 00:54:49 301
2020-05-14 00:54:50 300
2020-05-14 00:54:51 299
2020-05-14 00:54:52 298
2020-05-14 00:54:53 297
2020-05-14 00:54:54 296
2020-05-14 00:54:55 295
.......
2020-05-14 00:59:44 6
2020-05-14 00:59:45 5
2020-05-14 00:59:46 4
2020-05-14 00:59:47 3
2020-05-14 00:59:48 2

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe