pub fn try_sleep(duration: Duration) -> Result<Sleep<'static>, TimerError>
Expand description
Returns a Future
that completes after the specified Duration
.
This function uses the global default timer, and the returned
Timeout
future will live for the 'static
lifetime. See the
module-level documentation for details on using the global default
timer.
§Returns
Ok
(
Sleep
)
if a newSleep
future was created successfully.Err
(
TimerError::NoGlobalTimer
)
if a global timer was not set by callingset_global_timer
first.Err
(
TimerError::DurationTooLong
)
if the requested sleep duration exceeds the global timer’s maximum sleep duration.
§Panics
This function does not panic. For a version of this function that panics
rather than returning a TimerError
, use sleep()
instead.
§Examples
use maitake::time;
async fn example() {
// try to sleep for one second
match time::try_sleep(time::Duration::from_secs(1)) {
// the sleep future was created successfully, so we can now await it.
Ok(sleep) => {
sleep.await;
println!("one second has passed!");
},
Err(time::TimerError::NoGlobalTimer) =>
println!("timer is not initialized"),
Err(time::TimerError::DurationTooLong { .. }) =>
unreachable!("1 second should not exceed the max duration"),
Err(error) => panic!("unexpected timer error: {error}"),
}
}