Skip to content

Tokio::spawn last woken time question #4101

Answered by Darksonn
Milo123459 asked this question in Q&A
Discussion options

You must be logged in to vote

This turns out to be rather tricky and requires a manual Future implementation. You can find one below. To use it, you would do tokio::spawn(PollTimeout::new(your_task, duration)).

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 p…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@Milo123459
Comment options

@Milo123459
Comment options

@hawkw
Comment options

@Milo123459
Comment options

Answer selected by Milo123459
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants