There is a costly API call that takes couple of seconds and writes a lot of data. I try to limit the calls made to once every interval
seconds. The problem is, that IF the API gets called, it usually gets called multiple times at once.
So what I did:
class LimitAPICalls:
def decide_for_poll(self, interval):
self.time_now = datetime.datetime.now()
try:
time_since_last_run = (self.time_now - self.time_old).seconds
except Exception as E:
time_since_last_run = interval
if time_since_last_run >= interval:
self.time_old = datetime.datetime.now()
return True
return False
def call_wrapper(self):
if self.decide_for_poll(interval = 30) == True:
print("actually calling")
self.result = the_call_itself()
try:
print("returning values from memory")
return self.result
except AttributeError:
print("calling because of AttributeError")
self.time_old = datetime.datetime.now()
return the_call_itself()
What I see in the console, specially when reinitializing, is more or less always the time a pattern similar to:
actually calling
returning values from memoryreturning values from memory
returning values from memorycalling because of AttributeError
calling because of AttributeError
calling because of AttributeError
returning values from memory
calling because of AttributeError
returning values from memory returning values from memory
returning values from memory returning values from memoryreturning values from memory
returning values from memory
But what I want is that the first call ensures that for the time of the interval
is the only call being made. So the call is being made multipe times, because it is not finished yet.
The calls come from the browser, all of them at once - how do I ensure that only one call is made in the time of interval
?