mirror of
https://github.com/guilhermewerner/mini-redis
synced 2025-06-15 14:35:13 +00:00
49 lines
1.1 KiB
Rust
49 lines
1.1 KiB
Rust
#![allow(non_snake_case)]
|
|
|
|
use std::future::Future;
|
|
use std::pin::Pin;
|
|
use std::task::{Context, Poll};
|
|
use std::thread;
|
|
use std::time::{Duration, Instant};
|
|
|
|
struct Delay {
|
|
when: Instant,
|
|
}
|
|
|
|
impl Future for Delay {
|
|
type Output = &'static str;
|
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<&'static str> {
|
|
if Instant::now() >= self.when {
|
|
println!("Hello world");
|
|
Poll::Ready("done")
|
|
} else {
|
|
// Get a handle to the waker for the current task
|
|
let waker = cx.waker().clone();
|
|
let when = self.when;
|
|
|
|
// Spawn a timer thread.
|
|
thread::spawn(move || {
|
|
let now = Instant::now();
|
|
|
|
if now < when {
|
|
thread::sleep(when - now);
|
|
}
|
|
|
|
waker.wake();
|
|
});
|
|
|
|
Poll::Pending
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() {
|
|
let when = Instant::now() + Duration::from_millis(100);
|
|
let future = Delay { when };
|
|
|
|
let out = future.await;
|
|
assert_eq!(out, "done");
|
|
}
|