@@ -10,9 +10,15 @@ pub use instant::Instant;
10
10
use std:: future:: Future ;
11
11
use std:: pin:: Pin ;
12
12
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
+ } ;
14
17
15
- use crate :: { iter:: AsyncIterator , runtime:: Reactor } ;
18
+ use crate :: {
19
+ iter:: AsyncIterator ,
20
+ runtime:: { AsyncPollable , Reactor } ,
21
+ } ;
16
22
17
23
/// A measurement of the system clock, useful for talking to external entities
18
24
/// like the file system or other processes.
@@ -47,28 +53,26 @@ impl AsyncIterator for Interval {
47
53
}
48
54
49
55
#[ derive( Debug ) ]
50
- pub struct Timer ( Option < Instant > ) ;
56
+ pub struct Timer ( Option < AsyncPollable > ) ;
51
57
52
58
impl Timer {
53
59
pub fn never ( ) -> Timer {
54
60
Timer ( None )
55
61
}
56
62
pub fn at ( deadline : Instant ) -> Timer {
57
- Timer ( Some ( deadline) )
63
+ let pollable = Reactor :: current ( ) . schedule ( subscribe_instant ( * deadline) ) ;
64
+ Timer ( Some ( pollable) )
58
65
}
59
66
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) )
61
69
}
62
70
pub fn set_after ( & mut self , duration : Duration ) {
63
71
* self = Self :: after ( duration) ;
64
72
}
65
73
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 ,
72
76
None => std:: future:: pending ( ) . await ,
73
77
}
74
78
}
@@ -89,4 +93,16 @@ impl Future for Timer {
89
93
#[ cfg( test) ]
90
94
mod test {
91
95
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
+ }
92
108
}
0 commit comments