Function tokio::time::sleep_until
source · Expand description
Waits until deadline
is reached.
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.
To run something regularly on a schedule, see interval
.
Cancellation
Canceling a sleep instance is done by dropping the returned future. No additional cleanup work is required.
Examples
Wait 100ms and print “100 ms have elapsed”.
use tokio::time::{sleep_until, Instant, Duration};
#[tokio::main]
async fn main() {
sleep_until(Instant::now() + Duration::from_millis(100)).await;
println!("100 ms have elapsed");
}
See the documentation for the Sleep
type for more examples.
Panics
This function panics if there is no current timer set.
It can be triggered when Builder::enable_time
or
Builder::enable_all
are not included in the builder.
It can also panic whenever a timer is created outside of a
Tokio runtime. That is why rt.block_on(sleep(...))
will panic,
since the function is executed outside of the runtime.
Whereas rt.block_on(async {sleep(...).await})
doesn’t panic.
And this is because wrapping the function on an async makes it lazy,
and so gets executed inside the runtime successfully without
panicking.