Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp
Created January 12, 2023 15:47
Show Gist options
  • Save eduardonunesp/dbd7f6c10f1bcacc4b1e5284591120f4 to your computer and use it in GitHub Desktop.
Save eduardonunesp/dbd7f6c10f1bcacc4b1e5284591120f4 to your computer and use it in GitHub Desktop.
Example of sync function wrapped into a future for the tokio runtime
use std::{thread, time};
use futures::future;
use std::time::Instant;
// Delay function will wait for n seconds
async fn delay(secs: u64) -> anyhow::Result<()> {
let ten_secs = time::Duration::from_secs(secs);
let now = time::Instant::now();
// Wraps a sync call into a future
future::ok({
thread::sleep(ten_secs);
}).await
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let start = Instant::now();
let secs_to_wait = 2;
// Creates the future to be resolved sometime
let op = delay(secs_to_wait);
println!("This will print immediately");
// Await the async function to be resolved
op.await?;
println!("This will print after {secs_to_wait} seconds");
let duration = start.elapsed();
println!("Duration of the program {:?}", duration);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment