1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
mod waitable_objects;
use std::{
time::Duration,
sync::RwLock,
ffi::c_void,
process::abort
};
use windows::Win32::{
Foundation::{HANDLE, BOOLEAN, ERROR_IO_PENDING},
System::Threading::*,
};
use super::timer::{CallbackHint, Result};
use waitable_objects::{ManualResetEvent, get_last_error, get_win32_last_error, to_result};
pub struct TimerQueue {
handle: HANDLE
}
pub struct Timer<'q, 'h> {
queue: &'q TimerQueue,
handle: HANDLE,
callback: Box<MutWrapper<'h>>
}
struct CriticalSection<'e> {
event: &'e mut ManualResetEvent
}
struct MutWrapper<'h> {
f: Box<dyn FnMut() + 'h>,
executing: ManualResetEvent,
mark_deleted: RwLock<bool>
}
impl<'e> CriticalSection<'e> {
fn new(r#ref: &'e mut ManualResetEvent) -> Self {
r#ref.reset().unwrap();
Self { event: r#ref }
}
}
impl<'e> Drop for CriticalSection<'e> {
fn drop(&mut self) {
self.event.set().unwrap();
}
}
impl<'h> MutWrapper<'h> {
fn new<F>(handler: F) -> Self where F: FnMut() + Send + 'h {
MutWrapper::<'h> {
f: Box::new(handler),
executing: ManualResetEvent::new_init(true),
mark_deleted: RwLock::new(false)
}
}
fn call(&mut self) -> Result<()> {
let is_deleted = self.mark_deleted.read().unwrap();
if !*is_deleted {
let cs = CriticalSection::new(&mut self.executing);
(self.f)();
drop(cs);
}
Ok(())
}
}
impl TimerQueue {
pub fn new() -> Self {
unsafe { Self { handle: CreateTimerQueue().unwrap() } }
}
pub fn schedule_timer<'q, 'h, F>(&'q self, due: Duration, period: Duration, hints: Option<CallbackHint>, handler: F) -> Result<Timer<'q, 'h>>
where F: FnMut() + Send + 'h
{
let period = period.as_millis() as u32;
let option = hints.map(|o| match o {
CallbackHint::QuickFunction => WT_EXECUTEINPERSISTENTTHREAD,
CallbackHint::SlowFunction => WT_EXECUTELONGFUNCTION,
}).unwrap_or(WT_EXECUTEDEFAULT);
let option = if period == 0 { option | WT_EXECUTEONLYONCE } else { option };
let mut timer_handle = HANDLE::default();
let callback = Box::new(MutWrapper::new(handler));
let callback_ref = callback.as_ref() as *const MutWrapper as *const c_void;
let create_timer_queue_timer_result = unsafe {
CreateTimerQueueTimer(&mut timer_handle, self.handle, Some(timer_callback), Some(callback_ref),
due.as_millis() as u32, period, option).as_bool()
};
if create_timer_queue_timer_result {
Ok(Timer::<'q,'h> { queue: self, handle: timer_handle, callback })
} else {
Err(get_last_error())
}
}
pub const fn default() -> Self {
Self { handle: HANDLE(0) }
}
}
extern "system" fn timer_callback(ctx: *mut c_void, _: BOOLEAN) {
let wrapper = unsafe { &mut *(ctx as *mut MutWrapper) };
if let Err(e) = wrapper.call() {
println!("WARNING: Error occurred during timer callback: {e:?}");
}
}
impl Default for TimerQueue {
fn default() -> Self {
TimerQueue::default()
}
}
impl Drop for TimerQueue {
fn drop(&mut self) {
if !self.handle.is_invalid() {
assert!(unsafe { DeleteTimerQueue(self.handle).as_bool() });
self.handle = HANDLE::default();
}
}
}
impl<'q,'h> Timer<'q,'h> {
pub fn change_period(&self, due: Duration, period: Duration) -> Result<()> {
to_result(unsafe { ChangeTimerQueueTimer(self.queue.handle, self.handle, due.as_millis() as u32, period.as_millis() as u32).as_bool() })
}
}
const EXPECTED_EXECUTION_TIME: Duration = Duration::from_secs(2);
impl<'q, 'h> Drop for Timer<'q, 'h> {
fn drop(&mut self) {
if !self.handle.is_invalid() {
let mut is_deleted = self.callback.mark_deleted.write().unwrap();
*is_deleted = true;
self.change_period(Duration::default(), Duration::default()).unwrap();
if !self.callback.executing.wait_one(EXPECTED_EXECUTION_TIME).unwrap() {
println!("ERROR: Wait for execution timed out! Timer handler is being executed while timer is also being destroyed! Program aborts!");
abort();
}
let result = unsafe { DeleteTimerQueueTimer(self.queue.handle, self.handle, None).as_bool() };
if !result {
let e = get_win32_last_error();
if e != ERROR_IO_PENDING {
println!("WARNING: Delete timer failed with error {e:?}. No retry attempt. Memory might leak!");
}
}
self.handle = HANDLE::default();
}
}
}
#[cfg(test)]
mod test {
use std::{
thread::sleep,
time::Duration
};
use super::TimerQueue;
#[test]
fn test_singleshot(){
let my_queue = TimerQueue::new();
let mut called = 0;
let timer = my_queue.schedule_timer(Duration::from_millis(400), Duration::ZERO, None, || called += 1).unwrap();
sleep(Duration::from_secs(1));
drop(timer);
assert_eq!(called, 1);
}
#[test]
fn test_period(){
let my_queue = TimerQueue::new();
let mut called = 0;
let duration = Duration::from_millis(300);
let t = my_queue.schedule_timer(duration, duration, None, || called += 1).unwrap();
sleep(Duration::from_secs(1));
drop(t);
assert_eq!(called, 3);
}
}