I have multiple threads running the same process that need to be able to to notify each other that something should not be worked on for the next n seconds its not the end of the world if they do however.
My aim is to be able to pass a string and a TTL to the cache and be able to fetch all the strings that are in the cache as a list. The cache can live in memory and the TTL's will be no more than 20 seconds.
Does anyone have a any suggestions for how this can be accomplished?
In case you don't want to use any 3rd libraries, you can add one more parameter to your expensive function:
ttl_hash=None
. This new parameter is so-called "time sensitive hash", its the only purpose is to affectlru_cache
.For example:
I absolutely love the idea from @iutinvg, I just wanted to take it a little further. Decouple it from having to know to pass the
ttl
and just make it a decorator so you don't have to think about it. If you havedjango
,py3
and don't feel like pip installing any dependencies, try this out.The OP is using python 2.7 but if you're using python 3,
ExpiringDict
mentioned in the accepted answer is currently, well, expired. The last commit to the github repo was June 17, 2017 and there is an open issue that it doesn't work with Python 3.5There is a more recently maintained project cachetools (last commit Jun 14, 2018)
pip install cachetools
ttl
is the time to live in seconds.Regarding an expiring in-memory cache, for general purpose use, a common design pattern to typically do this is not via a dictionary, but via a function or method decorator. A cache dictionary is managed behind the scenes. As such, this answer somewhat complements the answer by User which uses a dictionary rather than a decorator.
The
ttl_cache
decorator incachetools==3.1.0
works a lot likefunctools.lru_cache
, but with a time to live.Something like that ?
You can use the
expiringdict
module:In the description they do not talk about multithreading, so in order not to mess up, use a
Lock
.