use std::collections::HashMap;
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::sync::RwLock;
use crate::archive::types::TaskResult;
#[allow(dead_code)]
pub struct TaskManager {
runtime: Handle,
tasks: Arc<RwLock<HashMap<String, TaskResult>>>,
}
#[allow(dead_code)]
impl TaskManager {
pub fn new(runtime: Handle) -> Self {
Self {
runtime,
tasks: Arc::new(RwLock::new(HashMap::new())),
}
}
pub fn spawn_blocking<F>(&self, task_id: String, f: F)
where
F: FnOnce() -> TaskResult + Send + 'static,
{
let tasks = self.tasks.clone();
self.runtime.spawn(async move {
let result = tokio::task::spawn_blocking(f).await;
match result {
Ok(task_result) => {
let mut tasks = tasks.write().await;
tasks.insert(task_id, task_result);
}
Err(e) => {
let mut tasks = tasks.write().await;
tasks.insert(
task_id,
TaskResult {
task_id: String::new(),
success: false,
message: format!("任务执行失败: {}", e),
output_path: None,
},
);
}
}
});
}
pub async fn get_result(&self, task_id: &str) -> Option<TaskResult> {
let tasks = self.tasks.read().await;
tasks.get(task_id).cloned()
}
}