Skip to content

Commit 87919ec

Browse files
committed
rewrite Timer in terms of AsyncPollable
1 parent c092763 commit 87919ec

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

src/time/mod.rs

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,15 @@ pub use instant::Instant;
1010
use std::future::Future;
1111
use std::pin::Pin;
1212
use std::task::{Context, Poll};
13-
use wasi::clocks::{monotonic_clock::subscribe_instant, wall_clock};
13+
use wasi::clocks::{
14+
monotonic_clock::{subscribe_duration, subscribe_instant},
15+
wall_clock,
16+
};
1417

15-
use crate::{iter::AsyncIterator, runtime::Reactor};
18+
use crate::{
19+
iter::AsyncIterator,
20+
runtime::{AsyncPollable, Reactor},
21+
};
1622

1723
/// A measurement of the system clock, useful for talking to external entities
1824
/// like the file system or other processes.
@@ -47,28 +53,26 @@ impl AsyncIterator for Interval {
4753
}
4854

4955
#[derive(Debug)]
50-
pub struct Timer(Option<Instant>);
56+
pub struct Timer(Option<AsyncPollable>);
5157

5258
impl Timer {
5359
pub fn never() -> Timer {
5460
Timer(None)
5561
}
5662
pub fn at(deadline: Instant) -> Timer {
57-
Timer(Some(deadline))
63+
let pollable = Reactor::current().schedule(subscribe_instant(*deadline));
64+
Timer(Some(pollable))
5865
}
5966
pub fn after(duration: Duration) -> Timer {
60-
Timer(Some(Instant::now() + duration))
67+
let pollable = Reactor::current().schedule(subscribe_duration(*duration));
68+
Timer(Some(pollable))
6169
}
6270
pub fn set_after(&mut self, duration: Duration) {
6371
*self = Self::after(duration);
6472
}
6573
pub async fn wait(&self) {
66-
match self.0 {
67-
Some(deadline) => {
68-
Reactor::current()
69-
.wait_for(subscribe_instant(*deadline))
70-
.await
71-
}
74+
match &self.0 {
75+
Some(pollable) => pollable.wait_for().await,
7276
None => std::future::pending().await,
7377
}
7478
}
@@ -89,4 +93,16 @@ impl Future for Timer {
8993
#[cfg(test)]
9094
mod test {
9195
use super::*;
96+
97+
#[test]
98+
fn timer_now() {
99+
crate::runtime::block_on(async {
100+
let start = Instant::now();
101+
let timer = Timer::at(start);
102+
let now = timer.await;
103+
let d = now.duration_since(start);
104+
let d: std::time::Duration = d.into();
105+
println!("timer_now awaited for {} s", d.as_secs_f32());
106+
});
107+
}
92108
}

0 commit comments

Comments
 (0)