39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
|
|
from collections import deque
|
|||
|
|
import threading
|
|||
|
|
|
|||
|
|
class TimestampedQueue:
|
|||
|
|
def __init__(self, maxlen):
|
|||
|
|
self.maxlen = maxlen
|
|||
|
|
self.queue = deque(maxlen=maxlen)
|
|||
|
|
self.lock = threading.Lock() # 可选,用于线程安全
|
|||
|
|
|
|||
|
|
def append(self, item):
|
|||
|
|
"""添加一个对象到队列"""
|
|||
|
|
with self.lock:
|
|||
|
|
self.queue.append(item)
|
|||
|
|
|
|||
|
|
def query_by_timestamp(self, target_timestamp):
|
|||
|
|
"""
|
|||
|
|
查询匹配 target_timestamp 的对象,并返回其前后各 50 个对象(或全部可用对象)
|
|||
|
|
返回: 匹配的对象 + 前后 50 个对象的列表(若无匹配则返回空列表)
|
|||
|
|
"""
|
|||
|
|
with self.lock:
|
|||
|
|
# 转换为列表以便索引访问
|
|||
|
|
items = list(self.queue)
|
|||
|
|
n = len(items)
|
|||
|
|
result = []
|
|||
|
|
|
|||
|
|
# 遍历查找匹配的 timestamp
|
|||
|
|
for i, item in enumerate(items):
|
|||
|
|
if item["timestamp"] == target_timestamp:
|
|||
|
|
# 计算前后范围
|
|||
|
|
start = max(0, i - 50)
|
|||
|
|
end = min(n, i + 50 + 1) # +1 因为切片不包含 end
|
|||
|
|
result = items[start:end]
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return str(list(self.queue))
|