lunarlonging's picture
Upload 58 files
190f7b3 verified
Raw
History Blame Contribute Delete
1.24 kB
use tokio::runtime::{Builder, Runtime};
use tokio_util::sync::CancellationToken;
pub struct BackgroundRuntime {
runtime: Option<Runtime>,
cancellation: CancellationToken,
}
impl BackgroundRuntime {
pub fn new() -> anyhow::Result<Self> {
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<F>(&self, future: F) -> anyhow::Result<F::Output>
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));
}
}
}