use tokio::runtime::{Builder, Runtime}; use tokio_util::sync::CancellationToken; pub struct BackgroundRuntime { runtime: Option, cancellation: CancellationToken, } impl BackgroundRuntime { pub fn new() -> anyhow::Result { let runtime = Builder::new_multi_thread() .worker_threads(2) .enable_all() .thread_name("xpost-archiver-worker") .build()?; let cancellation = CancellationToken::new(); Ok(Self { runtime: Some(runtime), cancellation, }) } pub fn cancellation_token(&self) -> CancellationToken { self.cancellation.clone() } pub fn block_on(&self, future: F) -> anyhow::Result where F: std::future::Future, { let runtime = self .runtime .as_ref() .ok_or_else(|| anyhow::anyhow!("后台运行时已关闭"))?; Ok(runtime.block_on(future)) } } impl Drop for BackgroundRuntime { fn drop(&mut self) { self.cancellation.cancel(); if let Some(runtime) = self.runtime.take() { runtime.shutdown_timeout(std::time::Duration::from_secs(3)); } } }