緩存鎖的一個(gè)思路(代碼未驗(yàn)證)
@contextmanager
def custom_lock(key, timeout):
"""如果有任務(wù)執(zhí)行, 返回任務(wù)執(zhí)行的時(shí)間, 單位返回s, 如果沒(méi)有任務(wù)執(zhí)行, 返回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 '已經(jīng)執(zhí)行了{(lán)0}ms'.format(t)
else:
do_something()