pub enum TimeService {
    RealTimeService(RealTimeService),
    MockTimeService(MockTimeService),
}
Expand description

TimeService abstracts all time-related operations in one place that can be easily mocked-out and controlled in tests or delegated to the actual underlying runtime (usually tokio). It’s provided as an enum so we don’t have to infect everything with a generic tag.

TimeService is async-focused: the sleep, interval, and timeout methods all return Futures and Streams. That said, TimeService supports non-async clients as well; simply use the sleep_blocking method instead of sleep. Note that the blocking call will actually block the current thread until the sleep time has elapsed.

TimeService tries to mirror the API provided by [tokio::time] to an extent. The primary difference is that all time is expressed in relative Durations. In other words, “sleep for 5s” vs “sleep until unix time 1607734460”. Absolute time is provided by TimeService::now which returns the current unix time.

Note: you must also include the TimeServiceTrait to use the actual time-related functionality.

Note: we have to provide our own Timeout and Interval types that use the Sleep future, since tokio’s implementations are coupled to its internal Sleep future.

Note: TimeService’s should be free (or very cheap) to clone and send around between threads. In production (without test features), this enum is a zero-sized type.

Variants§

§

RealTimeService(RealTimeService)

§

MockTimeService(MockTimeService)

Implementations§

source§

impl TimeService

source

pub fn real() -> Self

Create a new real, production time service that actually uses the systemtime.

See RealTimeService.

source

pub fn mock() -> Self

Create a mock, simulated time service that does not query the system time and allows fine-grained control over advancing time and waking sleeping tasks.

See MockTimeService.

source

pub fn into_mock(self) -> MockTimeService

Trait Implementations§

source§

impl Clone for TimeService

source§

fn clone(&self) -> TimeService

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for TimeService

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for TimeService

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl From<MockTimeService> for TimeService

source§

fn from(v: MockTimeService) -> TimeService

Converts to this type from the input type.
source§

impl From<RealTimeService> for TimeService

source§

fn from(v: RealTimeService) -> TimeService

Converts to this type from the input type.
source§

impl TimeServiceTrait for TimeService

source§

fn now(&self) -> Instant

Query a monotonically nondecreasing clock. Returns an opaque type that can only be compared to other Instants, i.e., this is a monotonic relative time whereas now_unix_time is a non-monotonic absolute time.

On Linux, this is equivalent to clock_gettime(CLOCK_MONOTONIC, _)

See Instant for more details.

source§

fn now_unix_time(&self) -> Duration

Query the current unix timestamp as a Duration.

When used on a TimeService::real(), this is equivalent to SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).

Note: the Duration returned from this function is NOT guaranteed to be monotonic. Use now if you need monotonicity.

From the SystemTime docs:

Distinct from the Instant type, this time measurement is not monotonic. This means that you can save a file to the file system, then save another file to the file system, and the second file has a SystemTime measurement earlier than the first. In other words, an operation that happens after another operation in real time may have an earlier SystemTime!

For example, the system administrator could clock_settime into the past, breaking clock time monotonicity.

On Linux, this is equivalent to clock_gettime(CLOCK_REALTIME, _).

source§

fn now_secs(&self) -> u64

Query the current unix timestamp in seconds.

Equivalent to self.now_unix_time().as_secs(). See now_unix_time.

source§

fn sleep(&self, __enum_dispatch_arg_0: Duration) -> Sleep

Return a Future that waits until duration has passed.

No work is performed while awaiting on the sleep future to complete. Sleep operates at millisecond granularity and should not be used for tasks that require high-resolution timers.

Cancelation

Canceling a sleep instance is done by dropping the returned future. No additional cleanup work is required.

source§

fn sleep_until(&self, __enum_dispatch_arg_0: Instant) -> Sleep

Return a Future that waits until the deadline.

If the deadline is in the past, the Sleep will trigger as soons as it’s polled.

See sleep for more details.

source§

fn sleep_blocking(&self, __enum_dispatch_arg_0: Duration)

Blocks the current thread until duration time has passed.

source§

fn interval(&self, __enum_dispatch_arg_0: Duration) -> Interval

Creates a new Interval that yields with interval of period. The first tick completes immediately. An interval will tick indefinitely.

Cancelation

At any time, the Interval value can be dropped. This cancels the interval.

Panics

This function panics if period is zero.

source§

fn interval_at( &self, __enum_dispatch_arg_0: Instant, __enum_dispatch_arg_1: Duration ) -> Interval

Creates a new Interval that yields with interval of period. The first tick completes after the start deadline. An interval will tick indefinitely.

See interval for more details.

source§

fn timeout<F: Future>( &self, __enum_dispatch_arg_0: Duration, __enum_dispatch_arg_1: F ) -> Timeout<F>

Require a Future to complete before the specified duration has elapsed.

If the future completes before the duration has elapsed, then the completed value is returned. Otherwise, Err(Elapsed) is returned and the future is canceled.

Cancelation

Cancelling a timeout is done by dropping the future. No additional cleanup or other work is required.

The original future may be obtained by calling Timeout::into_inner. This consumes the Timeout.

source§

fn timeout_at<F: Future>( &self, __enum_dispatch_arg_0: Instant, __enum_dispatch_arg_1: F ) -> Timeout<F>

Require a Future to complete before the deadline.

If the future completes before the duration has elapsed, then the completed value is returned. Otherwise, Err(Elapsed) is returned and the future is canceled.

See timeout for more details.

source§

impl TryInto<MockTimeService> for TimeService

§

type Error = &'static str

The type returned in the event of a conversion error.
source§

fn try_into( self ) -> Result<MockTimeService, <Self as TryInto<MockTimeService>>::Error>

Performs the conversion.
source§

impl TryInto<RealTimeService> for TimeService

§

type Error = &'static str

The type returned in the event of a conversion error.
source§

fn try_into( self ) -> Result<RealTimeService, <Self as TryInto<RealTimeService>>::Error>

Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.