From eeb36b64881a6bb9fb54582402e789d7e8444268 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Mon, 30 Jul 2018 17:55:52 +0200 Subject: [PATCH] Implement IOLoop based AsyncRateLimiter --- lib/tfw/decorators/rate_limiter.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/lib/tfw/decorators/rate_limiter.py b/lib/tfw/decorators/rate_limiter.py index 2f21eac..6fb020a 100644 --- a/lib/tfw/decorators/rate_limiter.py +++ b/lib/tfw/decorators/rate_limiter.py @@ -31,3 +31,22 @@ class RateLimiter: if seconds_to_next_call > 0: return seconds_to_next_call return 0 + + +class AsyncRateLimiter(RateLimiter): + def __init__(self, rate_per_second, ioloop): + self.ioloop = ioloop + self.last_callback = None + super().__init__( + rate_per_second=rate_per_second, + action=self.async_action + ) + + def async_action(self, seconds_to_next_call): + if self.last_callback: + self.ioloop.remove_timeout(self.last_callback) + + self.last_callback = self.ioloop.call_later( + seconds_to_next_call, + self.fun + )