refactor: 重构 WebSocket 处理部分,整理逻辑并优化性能 (#498)
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::sync::MutexGuard;
|
||||
@@ -7,7 +7,7 @@ use crate::config::VersionedConfig;
|
||||
|
||||
pub static TASK_STATUS_NOTIFIER: LazyLock<TaskStatusNotifier> = LazyLock::new(TaskStatusNotifier::new);
|
||||
|
||||
#[derive(Serialize, Default)]
|
||||
#[derive(Serialize, Default, Clone, Copy)]
|
||||
pub struct TaskStatus {
|
||||
is_running: bool,
|
||||
last_run: Option<chrono::DateTime<chrono::Local>>,
|
||||
@@ -17,13 +17,13 @@ pub struct TaskStatus {
|
||||
|
||||
pub struct TaskStatusNotifier {
|
||||
mutex: tokio::sync::Mutex<()>,
|
||||
tx: tokio::sync::watch::Sender<Arc<TaskStatus>>,
|
||||
rx: tokio::sync::watch::Receiver<Arc<TaskStatus>>,
|
||||
tx: tokio::sync::watch::Sender<TaskStatus>,
|
||||
rx: tokio::sync::watch::Receiver<TaskStatus>,
|
||||
}
|
||||
|
||||
impl TaskStatusNotifier {
|
||||
pub fn new() -> Self {
|
||||
let (tx, rx) = tokio::sync::watch::channel(Arc::new(TaskStatus::default()));
|
||||
let (tx, rx) = tokio::sync::watch::channel(TaskStatus::default());
|
||||
Self {
|
||||
mutex: tokio::sync::Mutex::const_new(()),
|
||||
tx,
|
||||
@@ -33,12 +33,12 @@ impl TaskStatusNotifier {
|
||||
|
||||
pub async fn start_running(&'_ self) -> MutexGuard<'_, ()> {
|
||||
let lock = self.mutex.lock().await;
|
||||
let _ = self.tx.send(Arc::new(TaskStatus {
|
||||
let _ = self.tx.send(TaskStatus {
|
||||
is_running: true,
|
||||
last_run: Some(chrono::Local::now()),
|
||||
last_finish: None,
|
||||
next_run: None,
|
||||
}));
|
||||
});
|
||||
lock
|
||||
}
|
||||
|
||||
@@ -49,12 +49,12 @@ impl TaskStatusNotifier {
|
||||
let config = VersionedConfig::get().load();
|
||||
let now = chrono::Local::now();
|
||||
|
||||
let _ = self.tx.send(Arc::new(TaskStatus {
|
||||
let _ = self.tx.send(TaskStatus {
|
||||
is_running: false,
|
||||
last_run,
|
||||
last_finish: Some(now),
|
||||
next_run: now.checked_add_signed(chrono::Duration::seconds(config.interval as i64)),
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/// 精确探测任务执行状态,保证如果读取到“未运行”,那么在锁释放之前任务不会被执行
|
||||
@@ -62,7 +62,7 @@ impl TaskStatusNotifier {
|
||||
self.mutex.try_lock().ok()
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<Arc<TaskStatus>> {
|
||||
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<TaskStatus> {
|
||||
self.rx.clone()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user