init
This commit is contained in:
55
src/data.rs
Normal file
55
src/data.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use tokio::sync::{Mutex, MutexGuard};
|
||||
|
||||
use crate::status::Status;
|
||||
|
||||
pub struct Data {
|
||||
pub status: Mutex<Status>,
|
||||
pub status_updated: Mutex<(Instant, bool)>,
|
||||
}
|
||||
|
||||
impl Data {
|
||||
pub fn new_sync() -> Self {
|
||||
Self {
|
||||
status: Mutex::new(Status::query_sync(false)),
|
||||
status_updated: Mutex::new((Instant::now(), false)),
|
||||
}
|
||||
}
|
||||
pub async fn new_async() -> Self {
|
||||
Self {
|
||||
status: Mutex::new(Status::query_async(false).await),
|
||||
status_updated: Mutex::new((Instant::now(), false)),
|
||||
}
|
||||
}
|
||||
pub fn status_sync(&self, dbg: bool) -> MutexGuard<Status> {
|
||||
let mut updated = self.status_updated.blocking_lock();
|
||||
let now = Instant::now();
|
||||
if (now - updated.0).as_secs_f32() > 3.0 || (dbg && !updated.1) {
|
||||
updated.0 = now;
|
||||
updated.1 = dbg;
|
||||
drop(updated);
|
||||
let mut lock = self.status.blocking_lock();
|
||||
*lock = Status::query_sync(dbg);
|
||||
lock
|
||||
} else {
|
||||
drop(updated);
|
||||
self.status.blocking_lock()
|
||||
}
|
||||
}
|
||||
pub async fn status_async(&self, dbg: bool) -> MutexGuard<Status> {
|
||||
let mut updated = self.status_updated.lock().await;
|
||||
let now = Instant::now();
|
||||
if (now - updated.0).as_secs_f32() > 3.0 || (dbg && !updated.1) {
|
||||
updated.0 = now;
|
||||
updated.1 = dbg;
|
||||
drop(updated);
|
||||
let mut lock = self.status.lock().await;
|
||||
*lock = Status::query_async(dbg).await;
|
||||
lock
|
||||
} else {
|
||||
drop(updated);
|
||||
self.status.lock().await
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user