Repository navigation
why doesnt Tokio 's File struct have a set_times function? #8451
|
std::fs::File has a function set_times to set the last accessed and modified times of a file. Yet I noticed that Tokio's File struct doesn't have this function. Why? |
Replies: 2 comments 3 replies
|
If there is no good reason for why this is, I could submit a issue about it. |
|
The absence of 1. The MSRV ConstraintIn the standard library, Tokio maintains a conservative MSRV policy across the 2. How Tokio Handles File I/O Under the HoodUnlike network sockets (which notify the OS event loop via non-blocking readiness through Therefore, Working Solutions TodayDepending on your architecture, here are the two standard, idiomatic ways to update file timestamps in an async Tokio application today: Pattern A: Direct Async Helper (Best when you have the path)If you know the path of the file, offload the call to use std::fs::FileTimes;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
pub async fn async_set_file_times(
path: impl AsRef<Path>,
accessed: Option<SystemTime>,
modified: Option<SystemTime>,
) -> std::io::Result<()> {
let path: PathBuf = path.as_ref().to_path_buf();
tokio::task::spawn_blocking(move || {
let mut times = FileTimes::new();
if let Some(atime) = accessed {
times = times.set_accessed(atime);
}
if let Some(mtime) = modified {
times = times.set_modified(mtime);
}
let file = std::fs::OpenOptions::new()
.write(true)
.open(&path)?;
file.set_times(times)
})
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?
}Pattern B: From an Existing
|
It's because the stdlib function
set_timeswas added after Tokio'sFiletype was written.