gpt4 book ai didi

python - 值在 python 中过期的容器

转载 作者:太空狗 更新时间:2023-10-30 00:57:50 33 4
gpt4 key购买 nike

我正在寻找一个线程安全的 Python 容器,其中的值会在一段时间后自动删除。这样的类存在吗?

最佳答案

这是 ExpireCounter 的线程安全版本:

import datetime
import collections
import threading

class ExpireCounter:
"""Tracks how many events were added in the preceding time period
"""

def __init__(self, timeout=1):
self.lock=threading.Lock()
self.timeout = timeout
self.events = collections.deque()

def add(self,item):
"""Add event time
"""
with self.lock:
self.events.append(item)
threading.Timer(self.timeout,self.expire).start()

def __len__(self):
"""Return number of active events
"""
with self.lock:
return len(self.events)

def expire(self):
"""Remove any expired events
"""
with self.lock:
self.events.popleft()

def __str__(self):
with self.lock:
return str(self.events)

可以这样使用:

import time
c = ExpireCounter()
assert(len(c) == 0)
print(c)
# deque([])

c.add(datetime.datetime.now())
time.sleep(0.75)
c.add(datetime.datetime.now())
assert(len(c) == 2)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 91426), datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])

time.sleep(0.75)
assert(len(c) == 1)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])

关于python - 值在 python 中过期的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4219843/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com