52 lines
2.3 KiB
Python
52 lines
2.3 KiB
Python
from PySide6.QtCore import QThread, Signal
|
||
from .msg_recorder import MessageRecorder
|
||
|
||
"""
|
||
定时查询消息数据库, 并发送最新的消息数据
|
||
"""
|
||
|
||
class MsgQueryThread(QThread):
|
||
# 定义信号:发送消息类型(1=系统,2=预警)和 消息信息列表
|
||
new_messages = Signal(int, list) # (message_type, [(content, is_processed, create_time, last_modified), ...])
|
||
|
||
def __init__(self, interval=1000, query_limit = 16):
|
||
super().__init__()
|
||
self.interval = interval # 查询间隔(毫秒)
|
||
self.query_limit = query_limit # 单次查询的项目条数,如每次查询16条消息
|
||
self.running = True # 线程运行标志
|
||
self.recorder = MessageRecorder() # 消息管理器
|
||
|
||
# 记录上次查询到的“最新last_modified时间”(按类型区分)
|
||
self.last_normal_modified = ""
|
||
self.last_warning_modified = ""
|
||
|
||
def run(self):
|
||
"""线程主逻辑: 每隔interval查询一次消息"""
|
||
while self.running:
|
||
# 1. 处理系统消息(类型1)
|
||
normal_msgs = self.recorder.get_latest_normal_messages(self.query_limit)
|
||
if normal_msgs:
|
||
# 找到这16条消息中最新的last_modified时间(即最大的)
|
||
latest_modified = max([msg[3] for msg in normal_msgs]) # msg[3]是last_modified
|
||
# 比较是否有更新(新增或状态变化)
|
||
# 注意:是根据last_modified来决定是否进行界面更新的
|
||
if latest_modified != self.last_normal_modified:
|
||
self.last_normal_modified = latest_modified
|
||
self.new_messages.emit(1, normal_msgs) # 发送信号更新UI,1表示系统消息
|
||
|
||
# 2. 处理预警消息(类型2)
|
||
warning_msgs = self.recorder.get_latest_warning_messages(self.query_limit)
|
||
if warning_msgs:
|
||
latest_modified = max([msg[3] for msg in warning_msgs])
|
||
if latest_modified != self.last_warning_modified:
|
||
self.last_warning_modified = latest_modified
|
||
self.new_messages.emit(2, warning_msgs)
|
||
|
||
self.msleep(self.interval)
|
||
|
||
def stop(self):
|
||
"""停止消息查询线程"""
|
||
self.running = False
|
||
self.wait(500)
|
||
if self.isRunning():
|
||
self.terminate() |