pub struct FromWatchedFile<T> { /* private fields */ }Expand description
FromWatchedFile is a struct that reads a file and watches for changes to the file. When the file changes, the struct will reload the file and update the value in the background. This struct is useful for reloading configuration files or other files that are read frequently. It is thread safe. Note: Each FromWatchedFile spawns a new thread to watch the file do not use too many of them!
// Your load function can return Option<T> where T is the desired type
// If your function returns None, the file will not be reloaded, and the current modified version
// of the file is not retried. Until it is modified again.
fn load_file_from_bytes(bytes: &[u8]) -> Result<String, FileParseError> {
Ok(String::from_utf8_lossy(bytes).to_string())
}
// Initialize the FromWatchedFile struct
let cfg: FromWatchedFile<String> = FromWatchedFile::new("config.json", load_file_from_bytes, Duration::from_secs(5));
let config = cfg.get();
match config {
Ok(c) => {
println!("Config: {}", c); // c is Arc of your type. Cloned on each get - pointer only
// Do something with the config
// whenever you call .get(), it is the current version of the config.
},
Err(cause) => println!("Config not loaded yet"),
// err is the first cause if it ever happens. Because subsequent load is either successful (no error),
// or error (no replace). So the cache always keep a valid copy of the reference if it ever happened.
}Implementations§
Source§impl<T> FromWatchedFile<T>
impl<T> FromWatchedFile<T>
Sourcepub fn new<F>(file_path: &str, parser: F, interval: Duration) -> Self
pub fn new<F>(file_path: &str, parser: F, interval: Duration) -> Self
Create a new FromWatchedFile struct and spawn a new thread with given interval and converter function. Converter function converts a slice of bytes to the desired type.
The file will be check based on interval. On change detected, the parser will be used to convert the file content to desired type.
You can get the latest copy using the get method.
Upon initialization, the first copy will be constructed.
The code never fails. If the file gone missing, or the file is not readable, the value will be None.
Sourcepub fn get<'a>(&'a self) -> Result<Arc<T>, FileParseError>
pub fn get<'a>(&'a self) -> Result<Arc<T>, FileParseError>
Get the desired converted type from the file If the file become not readable, it will return the last good copy.