Sub topic 7
Async timers and I/O
This chapter assumes you can write an async fn, use .await, and start a Tokio runtime with #[tokio::main]. It also assumes you know Result and ?. The examples use Tokio with the full feature in Cargo.toml.
[dependencies]
tokio = { version = "1", features = ["full"] }What timers and I/O have in common
Almost every real async program waits for one of two things: time to pass, or the operating system to finish an I/O operation. Both fit the model from the earlier chapters. A leaf future tries to make progress, and if it cannot, it stores the task's waker and returns Poll::Pending. Something outside the future later calls the waker.
For timers, that something is the runtime's timer wheel. For I/O, it is the runtime's reactor. The reactor registers sockets with the OS notification system (epoll on Linux, kqueue on macOS and BSD, IOCP on Windows) and wakes tasks when their sockets become ready.
While the task is pending, no thread is blocked on it. The worker thread runs other tasks.
Sleeping and measuring time
tokio::time::sleep returns a future that completes after a duration. Awaiting it suspends only the current task.
use std::time::Duration;
use tokio::time::{sleep, Instant};
#[tokio::main]
async fn main() {
let start = Instant::now();
sleep(Duration::from_millis(250)).await;
println!("waited at least {} ms", start.elapsed().as_millis());
}A sleep never finishes early, but it can finish late if the runtime is busy. Treat the duration as a lower bound.
tokio::time::Instant is a drop-in replacement for std::time::Instant. It lets Tokio's test utilities pause and advance the clock, which makes time-based tests fast.
Repeating work with interval
Use interval for work that repeats on a schedule. It is more accurate than looping over sleep, because a sleep loop adds the work's own duration to every period.
use std::time::Duration;
use tokio::time::interval;
#[tokio::main]
async fn main() {
let mut ticker = interval(Duration::from_millis(100));
for i in 0..3 {
ticker.tick().await;
println!("tick {i}");
}
}Two details cause confusion:
- The first
tick()completes immediately. Callticker.tick().awaitonce before the loop if you want to skip it, or useinterval_atto choose the start time. - If the loop body takes longer than the period, ticks are missed. By default Tokio then fires the missed ticks back to back to catch up. You can change this with
ticker.set_missed_tick_behavior(MissedTickBehavior::Delay)orSkip.
Deadlines with timeout
timeout wraps any future. It returns Ok(output) if the future finishes in time and Err(Elapsed) if it does not. On timeout the inner future is dropped, which cancels it. The cancellation chapter covers the consequences.
When the inner future is itself fallible, you get a nested result. Convert the Elapsed error into an error type your function already returns.
use std::io;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::time::timeout;
async fn connect_with_deadline(addr: &str) -> io::Result<TcpStream> {
match timeout(Duration::from_secs(2), TcpStream::connect(addr)).await {
Ok(result) => result,
Err(_) => Err(io::Error::new(io::ErrorKind::TimedOut, "connect timed out")),
}
}
#[tokio::main]
async fn main() {
match connect_with_deadline("127.0.0.1:9").await {
Ok(_) => println!("connected"),
Err(e) => println!("failed: {e}"),
}
}Async I/O traits
Tokio defines its own I/O traits, AsyncRead and AsyncWrite, whose methods poll instead of blocking. You rarely call those methods directly. The extension traits AsyncReadExt and AsyncWriteExt in tokio::io add the convenient async methods, and you must import them to use these methods.
| Method | Behavior |
|---|---|
| `read(&mut buf)` | Reads some bytes, possibly fewer than `buf.len()`. Returns `Ok(0)` at end of stream. |
| `read_exact(&mut buf)` | Fills `buf` completely or returns an `UnexpectedEof` error. |
| `read_to_end(&mut vec)` | Reads until end of stream. |
| `write(&buf)` | Writes some bytes and returns how many. |
| `write_all(&buf)` | Writes every byte, looping internally. |
| `flush()` | Pushes buffered data to the underlying destination. |
The most common mistake is treating read as if it filled the buffer. It returns whatever is available, and TCP does not preserve message boundaries. Use read_exact, or a length prefix or delimiter, when you need a full message. For write, prefer write_all unless you handle partial writes yourself.
Files
tokio::fs mirrors std::fs with async functions. On most platforms the OS offers no truly async file API, so Tokio runs each file operation on its blocking thread pool and gives you a future for the result. You get a responsive runtime, but each call has some thread-hand-off overhead. For many small reads, read the whole file once rather than issuing many tiny operations.
use tokio::fs;
use tokio::io::AsyncWriteExt;
#[tokio::main]
async fn main() -> std::io::Result<()> {
fs::write("hello.txt", "hello\n").await?;
let mut file = fs::OpenOptions::new()
.append(true)
.open("hello.txt")
.await?;
file.write_all(b"world\n").await?;
file.flush().await?;
let text = fs::read_to_string("hello.txt").await?;
print!("{text}");
Ok(())
}The flush().await matters. tokio::fs::File buffers writes internally and performs them on a background thread. If you drop the file without flushing, the data may not be written yet, and you will not see an error.
Networking
Sockets are where the reactor does real work. TcpListener, TcpStream, and UdpSocket in tokio::net use non-blocking sockets and register them with the reactor. The next program is self-contained. It binds to port 0 so the OS picks a free port, runs an echo server in a spawned task, and connects to it as a client.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let addr = listener.local_addr()?;
tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 1024];
loop {
let n = socket.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
socket.write_all(&buf[..n]).await.unwrap();
}
});
let mut client = TcpStream::connect(addr).await?;
client.write_all(b"ping").await?;
let mut reply = [0u8; 4];
client.read_exact(&mut reply).await?;
println!("{}", String::from_utf8_lossy(&reply));
Ok(())
}The program prints ping. The client uses read_exact because it knows the reply is four bytes. The server uses read and echoes whatever arrived. A real server would loop over accept() and spawn one task per connection, which the next chapters build on.
Feature flags
Tokio's capabilities sit behind Cargo features. With full everything is on. In a library or a size-conscious binary, enable only what you use.
| Feature | Enables |
|---|---|
| `time` | `sleep`, `interval`, `timeout` |
| `net` | `TcpListener`, `TcpStream`, `UdpSocket` |
| `fs` | `tokio::fs` |
| `io-util` | `AsyncReadExt`, `AsyncWriteExt` |
| `rt`, `rt-multi-thread`, `macros` | The runtime and `#[tokio::main]` |
A missing feature produces a compile error such as "unresolved import" or "no method named read_exact". Check the features first before searching for another cause.
Common errors
- Forgetting
.awaiton a timer. The compiler warns that the future must be used, and nothing is delayed. - Importing
std::io::Readinstead oftokio::io::AsyncReadExt, so.read(...).awaitdoes not compile. - Assuming the first
intervaltick waits a full period. - Using blocking
std::fsorstd::netcalls inside tasks, which stalls the worker thread.
Exercise
A loop does let mut t = interval(Duration::from_secs(1)); loop { t.tick().await; do_work().await; }. What happens on the first iteration, and what happens if do_work takes 3 seconds?
Show answer
The first tick() completes immediately, so do_work starts at once. If do_work takes 3 seconds, two ticks are missed. With the default MissedTickBehavior::Burst, the next two tick() calls return immediately to catch up. To avoid the burst and keep a one-second gap after each run, call t.set_missed_tick_behavior(MissedTickBehavior::Delay).
Exercise
Why does socket.read(&mut buf).await returning Ok(4) not mean the peer sent a complete message, and which methods fix this?
Show answer
read returns whatever bytes are available, up to the buffer size, and TCP is a byte stream with no message boundaries. Use read_exact when the length is known, or add a length prefix or delimiter to your protocol. Ok(0) is the only value that signals end of stream.