缓存锁的一个思路(代码未验证)

缓存锁的一个思路(代码未验证)

@contextmanager
def custom_lock(key, timeout):
    """如果有任务执行, 返回任务执行的时间, 单位返回s, 如果没有任务执行, 返回None"""
    value = cache.get(key)
    now = int(time.time() * 1000)
    if value:
        yield (now - int(value))
    else:
        if cache.add(key, now, timeout):
            yield
        else:
            yield int(cache.get(key))
    cache.delete(key)


with custom_lock(key) as t:
    if t is not None:
        print '已经执行了{0}ms'.format(t)
    else:
        do_something()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容