Skip to content

Timer trait for shared timeout/interval extensions #2959

@tisonkun

Description

@tisonkun

When building fastimer I realize that with a very simple trait:

pub trait MakeDelay { // Timer
    /// The future returned by the `delay`/`delay_until` method.
    type Delay: Future<Output = ()> + Send;

    /// Create a future that completes at the specified instant.
    fn delay_util(&self, at: Instant) -> Self::Delay;

    /// Create a future that completes after the specified duration.
    fn delay(&self, duration: Duration) -> Self::Delay {
        self.delay_util(make_instant_from_now(duration))
    }
}

We can implement many common timer related extensions in a runtime-agnostic way:

pub trait MakeDelayExt: MakeDelay {
    fn timeout<F: Future>(&self, duration: Duration, fut: F) -> Timeout<F, Self::Delay> { ... }
    fn timeout_at<F: Future>(&self, deadline: Instant, fut: F) -> Timeout<F, Self::Delay> { ... }
    fn interval(self, period: Duration) -> Interval<Self> where Self: Sized { ... }
    fn interval_at(self, at: Instant, period: Duration) -> Interval<Self> where Self: Sized { ... }
}

impl<T: MakeDelay> MakeDelayExt for T {}

I'm considering whether it's a good candidate (direction) for (finally) the standard library as common async traits and utilities, but IIRC some of async-wg's targets include such common interfaces.

What do you think? cc @taiki-e @yoshuawuyts @nrc

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions