Overview
Tokio’s time module provides several primitives for time-based operations:Sleep
Wait for a duration or until a specific instant
Interval
Execute code repeatedly at fixed intervals
Timeout
Bound the execution time of futures
Sleep
sleep
Waits until
duration has elapsed.Parameters:duration: How long to sleep
Sleep future that completes after the durationExample:No work is performed while awaiting on the sleep future.
Sleep operates at millisecond granularity and should not be used for high-resolution timing.sleep_until
Waits until
deadline is reached.Parameters:deadline: The instant to wait until
Sleep Type
TheSleep future returned by sleep and sleep_until can be pinned and reset.
Resets the
Sleep instance to a new deadline without creating a new future.Example:Interval
interval
Creates a new
Interval that yields every period.Parameters:period: Time between ticks
Interval streamExample:interval measures time since the last tick, not absolute time. If processing takes time, the next tick may happen sooner to maintain the overall rate.interval_at
Creates an interval that starts at a specific instant.Parameters:
start: When to start the first tickperiod: Time between subsequent ticks
Interval Methods
Waits for the next tick of the interval.Returns: The instant of the tickExample:
Resets the interval immediately, causing the next tick to happen after
period from now.MissedTickBehavior
Controls behavior when ticks are missed (e.g., if processing takes longer than the period).Variants:
Burst: Fires all missed ticks immediatelyDelay: Delays to maintain spacing (default)Skip: Skips missed ticks
Timeout
timeout
Requires a future to complete before a duration has elapsed.Parameters:
duration: Maximum time to waitfuture: The future to execute
Result<T::Output, Elapsed> - Ok with result or Err if timed outExample:timeout_at
Requires a future to complete before a deadline.Parameters:
deadline: The instant by which the future must completefuture: The future to execute
Instant
A measurement of a monotonically nondecreasing clock. Opaque and useful only with
Duration.Example:Instant Methods
Returns the current instant.
Returns the time elapsed since this instant.
Adds a duration to this instant, returning
None on overflow.Subtracts a duration from this instant, returning
None on underflow.Duration
Re-exported fromstd::time::Duration for convenience.
Practical Examples
Periodic Task Execution
Timeout with Retry
Debouncing
Testing with Time
Tokio provides
tokio::time::pause(), tokio::time::advance(), and tokio::time::resume() functions for testing time-dependent code. These require the test-util feature.Best Practices
Enable time driver
Ensure the runtime has the time driver enabled with
enable_time() or enable_all().Use appropriate granularity
Time operations work at millisecond granularity. Don’t rely on sub-millisecond precision.