rtime_rs

Crates.iortime_rs
lib.rsrtime_rs
version0.1.3
sourcesrc
created_at2022-05-11 23:11:56.047222
updated_at2022-05-11 23:18:35.1005
descriptionRetrieve the current time from remote servers
homepage
repositoryhttps://github.com/tidwall/rtime.rs
max_upload_size
id584918
size8,928
Josh Baker (tidwall)

documentation

https://docs.rs/rtime_rs/

README

rtime.rs

license crates.io version documentation

Retrieve the current time from remote servers.

It works by requesting timestamps from twelve very popular hosts over https. As soon as it gets at least three responses, it takes the two that have the smallest difference in time. And from those two it picks the one that is the oldest. Finally it ensures that the time is monotonic.

Using

Get the remote time with rtime_rs::now().

// Get the current internet time, returns chrono::DateTime<Utc>.
// Fails if the Internet is offline.
let now = rtime_rs::now().unwrap();  

println!("{}", now);

// OUTPUT: 
// 2022-05-11 23:05:49 UTC

Stay in sync

The rtime_rs::now() will be a little slow, usually 200 ms or more, because it must make a round trip to three or more remote servers to determine the correct time.

You can make it fast like the built-in std::time::SystemTime::now() by calling rtime_rs::sync() once at the start of your program.

// Start syncing with the Internet time. Timeouts after 15 seconds when the 
// Internet is offline.
rtime_rs::sync(Duration::from_secs(15)).unwrap(); 

// All following rtime_rs::now() calls will now be quick and without the need
// for checking its result, because they will never fail.
let now = rtime_rs::now().unwrap();  

println!("{}", now);

// OUTPUT:
// 2022-05-11 23:06:52.000072083 UTC

It's a good idea to call rtime_rs::sync() at the top of the main() function.

Commit count: 3

cargo fmt