Skip to content

Instantly share code, notes, and snippets.

@Bhupesh-V
Created July 22, 2022 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bhupesh-V/2a212fc87e397ea6e09b0b3bac809145 to your computer and use it in GitHub Desktop.
Save Bhupesh-V/2a212fc87e397ea6e09b0b3bac809145 to your computer and use it in GitHub Desktop.
# 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