spawned_concurrency/threads/
time.rs

1use std::time::Duration;
2
3use spawned_rt::threads::{self as rt, CancellationToken, JoinHandle};
4
5use super::{GenServer, GenServerHandle};
6
7pub struct TimerHandle {
8    pub join_handle: JoinHandle<()>,
9    pub cancellation_token: CancellationToken,
10}
11
12// Sends a message after a given period to the specified GenServer. The task terminates
13// once the send has completed
14pub fn send_after<T>(
15    period: Duration,
16    mut handle: GenServerHandle<T>,
17    message: T::CastMsg,
18) -> TimerHandle
19where
20    T: GenServer + 'static,
21{
22    let cancellation_token = CancellationToken::new();
23    let mut cloned_token = cancellation_token.clone();
24    let join_handle = rt::spawn(move || {
25        rt::sleep(period);
26        if !cloned_token.is_cancelled() {
27            let _ = handle.cast(message);
28        };
29    });
30    TimerHandle {
31        join_handle,
32        cancellation_token,
33    }
34}
35
36// Sends a message to the specified GenServe repeatedly after `Time` milliseconds.
37pub fn send_interval<T>(
38    period: Duration,
39    mut handle: GenServerHandle<T>,
40    message: T::CastMsg,
41) -> TimerHandle
42where
43    T: GenServer + 'static,
44{
45    let cancellation_token = CancellationToken::new();
46    let mut cloned_token = cancellation_token.clone();
47    let join_handle = rt::spawn(move || loop {
48        rt::sleep(period);
49        if cloned_token.is_cancelled() {
50            break;
51        } else {
52            let _ = handle.cast(message.clone());
53        };
54    });
55    TimerHandle {
56        join_handle,
57        cancellation_token,
58    }
59}