mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-05 13:51:21 +00:00
Refactor AsyncRateLimiter for ease of use (IOLoop passing)
This commit is contained in:
parent
eeb36b6488
commit
ee7adb10be
@ -4,6 +4,8 @@
|
|||||||
from functools import wraps, partial
|
from functools import wraps, partial
|
||||||
from time import time, sleep
|
from time import time, sleep
|
||||||
|
|
||||||
|
from tfw.decorators.lazy_property import lazy_property
|
||||||
|
|
||||||
|
|
||||||
class RateLimiter:
|
class RateLimiter:
|
||||||
def __init__(self, rate_per_second, action=sleep):
|
def __init__(self, rate_per_second, action=sleep):
|
||||||
@ -34,19 +36,25 @@ class RateLimiter:
|
|||||||
|
|
||||||
|
|
||||||
class AsyncRateLimiter(RateLimiter):
|
class AsyncRateLimiter(RateLimiter):
|
||||||
def __init__(self, rate_per_second, ioloop):
|
def __init__(self, rate_per_second, ioloop_factory):
|
||||||
self.ioloop = ioloop
|
self._ioloop_factory = ioloop_factory
|
||||||
self.last_callback = None
|
self._ioloop = None
|
||||||
|
self._last_callback = None
|
||||||
|
|
||||||
super().__init__(
|
super().__init__(
|
||||||
rate_per_second=rate_per_second,
|
rate_per_second=rate_per_second,
|
||||||
action=self.async_action
|
action=self.async_action
|
||||||
)
|
)
|
||||||
|
|
||||||
def async_action(self, seconds_to_next_call):
|
@lazy_property
|
||||||
if self.last_callback:
|
def ioloop(self):
|
||||||
self.ioloop.remove_timeout(self.last_callback)
|
return self._ioloop_factory()
|
||||||
|
|
||||||
self.last_callback = self.ioloop.call_later(
|
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,
|
seconds_to_next_call,
|
||||||
self.fun
|
self.fun
|
||||||
)
|
)
|
||||||
|
Loading…
Reference in New Issue
Block a user