Tokio sleep() vs interval()

From a practical perspective what is the difference between sleep and interval?

To quote from the docs:

Waits until duration has elapsed.
Equivalent to sleep_until(Instant::now() + duration). An asynchronous analog to std::thread::sleep.
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.

1 Like

Sleep once? Use sleep. Sleep in a loop? Use interval.

But what's different? Do they essentially do the same thing except that you can call interval.tick() to make it happen again?

This will, on average, run fewer times than once per second:

loop {

Because there is some time spent between the calls to sleep that is not counted. If you replace it with an Interval, then it will remember when the last tick was, and take any time spent between ticks into account.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.