Tokio::spawn last woken time question #4101
Answered
by
Darksonn
Milo123459
asked this question in
Q&A
-
How do I make a tokio::spawn automatically "kill itself" after its last woken time was more than 60 seconds ago? Suggestions appreciated! |
Beta Was this translation helpful? Give feedback.
Answered by
Darksonn
Sep 10, 2021
Replies: 1 comment 4 replies
-
This turns out to be rather tricky and requires a manual use tokio::time::{sleep, Sleep, Duration, Instant};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
pub struct PollTimeout<F> {
future: F,
sleep: Sleep,
duration: Duration,
}
impl<F> PollTimeout<F> {
pub fn new(future: F, duration: Duration) -> Self {
Self {
future,
sleep: sleep(duration),
duration,
}
}
}
impl<F: Future> Future for PollTimeout<F> {
type Output = Result<F::Output, TimeoutError>;
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<F::Output, TimeoutError>> {
let me = unsafe { Pin::into_inner_unchecked(self) };
let mut sleep = unsafe { Pin::new_unchecked(&mut me.sleep) };
let future = unsafe { Pin::new_unchecked(&mut me.future) };
if sleep.as_mut().poll(ctx).is_ready() {
return Poll::Ready(Err(TimeoutError {}));
}
sleep.reset(Instant::now() + me.duration);
future.poll(ctx).map(Ok)
}
}
struct TimeoutError {} |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
Milo123459
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This turns out to be rather tricky and requires a manual
Future
implementation. You can find one below. To use it, you would dotokio::spawn(PollTimeout::new(your_task, duration))
.