0

I have a function that calls an api endpoint - and I want to call it every second and wait for it's response - currently my code calls the function but it kills it after certain seconds:

urls = [...]
def get_url(url):
    return requests.post(url, data=data)
        
def run():
    print("starting a run...")
    with ThreadPoolExecutor(max_workers=50) as pool:
        req = pool.map(get_url, urls)
        res = list(req)
        success = 0
        for r in res:
            if r.status_code == 200:
                success += 1
        print(f'{success} successful requests')

if __name__ == "__main__":
    print("starting...")
    rt = RepeatedTimer(1, run)
    try:
        sleep(60)
    finally:
        rt.stop()

And the ReapetedTimer object is the courtesy of:

https://stackoverflow.com/a/38317060

How can I call the run() function every second for one minute - and just wait for their responses? So far this code kills the program after 60 seconds, and if I set the sleep() to a higher value it will call the function more than it should.

ashes999
  • 1,234
  • 1
  • 12
  • 36

1 Answers1

0

If you just want it to run every 60 seconds forever until you kill the process, do:

if __name__ == "__main__":
    print("starting...")
    while True:
        try:
            run()
        except:
           # handle error or pass
        sleep(60)

EDIT: run once a second for 60 seconds. I woudn't overthink it or pull in a dependency for this. Keep it simple:

if __name__ == "__main__":
    print("starting...")
    count = 0
    while count < 60:
        count += 1
        try:
            run()
        except:
           # handle error or pass
        sleep(1)
Cameron Sima
  • 5,086
  • 6
  • 28
  • 47