2

I am using time.sleep() to periodically check how many async calls have returned. I would like to know the best practice.

I am using async calls for certain services, and need to get the results back in certain time.

To simplify the discussion, let us just assume that a global variable num_calls_returned is used to track how many async calls have returned.

import datetime
import time

num_calls_returned = 0

start_time = datetime.datetime.now()
now = start_time
while num_calls_returned < 5 and now - start_time < datetime.timedelta(seconds=10):
    time.sleep(0.1)
    now = datetime.datetime.now()

The code above works, but I'd like to know the best practice. How bad is the code calling time.sleep()? Certainly the calculation of now and delta is a waste of CPU time, but I guess it's negligible.

user1057019
  • 107
  • 2
  • 4
  • 1
    Have you looked into [asyncio](https://docs.python.org/3/library/asyncio.html)? – Iain Shelvington Aug 26 '19 at 03:25
  • `time.sleep` uses minimal amounts of CPU – Iain Shelvington Aug 26 '19 at 03:29
  • It's not really clear what best practice is without knowing what you're trying to accomplish. If you're just awaiting for results, polling sort of defeats the purpose of async, as Iain mentions. Check https://stackoverflow.com/questions/53021448/multiple-async-requests-simultaneously – ggorlen Aug 26 '19 at 03:35
  • Seems the best API to use is Asyncio.gather, but it doesn’t have a timeout parameter. My app is a service to get data asynchronously from another service and return the results back in a given time interval – user1057019 Aug 26 '19 at 12:41

0 Answers0