From d609bfb16d7e62f7473958cb4361ae58383cfb45 Mon Sep 17 00:00:00 2001 From: jesopo Date: Fri, 20 Sep 2019 11:47:57 +0100 Subject: [PATCH] cache calculated "next expiration" time --- src/Cache.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Cache.py b/src/Cache.py index 7a72c1f2..09c0230f 100644 --- a/src/Cache.py +++ b/src/Cache.py @@ -4,6 +4,8 @@ class Cache(object): def __init__(self): self._items = {} + self._cached_expiration = None + def cache_key(self, key: str): return "sha1:%s" % hashlib.sha1(key.encode("utf8")).hexdigest() @@ -15,17 +17,24 @@ class Cache(object): def _cache(self, key: str, value: typing.Any, expiration: typing.Optional[float]) -> str: id = self.cache_key(key) + self._cached_expiration = None self._items[id] = [key, value, expiration] return id def next_expiration(self) -> typing.Optional[float]: + if not self._cached_expiration == None: + return self._cached_expiration + expirations = [value[-1] for value in self._items.values()] expirations = list(filter(None, expirations)) if not expirations: return None now = time.monotonic() expirations = [e-now for e in expirations] - return max(min(expirations), 0) + + expiration = max(min(expirations), 0) + self._cached_expiration = expiration + return expiration def expire(self): now = time.monotonic() @@ -35,6 +44,7 @@ class Cache(object): if expiration and expiration <= now: expired.append(id) for id in expired: + self._cached_expiration = None del self._items[id] def has_item(self, key: typing.Any) -> bool: @@ -44,6 +54,7 @@ class Cache(object): key, value, expiration = self._items[self.cache_key(key)] return value def remove(self, key: str): + self._cached_expiration = None del self._items[self.cache_key(key)] def get_expiration(self, key: typing.Any) -> float: