Python in-memory cache with time to live

后端 未结 8 1517
后悔当初
后悔当初 2020-12-04 23:24

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 o

8条回答
  •  温柔的废话
    2020-12-05 00:02

    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 affect lru_cache.

    For example:

    from functools import lru_cache
    import time
    
    
    @lru_cache()
    def my_expensive_function(a, b, ttl_hash=None):
        del ttl_hash  # to emphasize we don't use it and to shut pylint up
        return a + b  # horrible CPU load...
    
    
    def get_ttl_hash(seconds=3600):
        """Return the same value withing `seconds` time period"""
        return round(time.time() / seconds)
    
    
    # somewhere in your code...
    res = my_expensive_function(2, 2, ttl_hash=get_ttl_hash())
    # cache will be updated once in an hour
    
    

提交回复
热议问题