Created
July 22, 2022 08:05
-
-
Save Bhupesh-V/2a212fc87e397ea6e09b0b3bac809145 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A barebones cache with a TTL | |
import threading | |
import time | |
class Cache: | |
def __init__(self): | |
self.cache = {} | |
# 4 seconds | |
self.TTL = 4 | |
def get(self, key): | |
return self.cache[key] | |
def put(self, key, value): | |
if key not in self.cache: | |
self.cache[key] = value | |
threading.Timer(self.TTL, self.invalidateCacheKey, [key]).start() | |
def invalidateCacheKey(self, key): | |
if key in self.cache: | |
del self.cache[key] | |
c = Cache() | |
c.put("mykey", "myvalue") | |
for i in range(1, 10): | |
time.sleep(1) | |
print(c.get("mykey")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment