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
use {Async, Future, Stream, Sender};
use syncbox::ScheduledThreadPool;
use time::{SteadyTime, Duration};

/// Provides timeouts as a `Future` and periodic ticks as a `Stream`.
pub struct Timer {
    pool: ScheduledThreadPool,
}

impl Timer {
    /// Creates a new timer backed by a thread pool with 5 threads.
    pub fn new() -> Timer {
        Timer::with_capacity(5)
    }

    /// Creates a new timer backed by a thread pool with `capacity` threads.
    pub fn with_capacity(capacity: u32) -> Timer {
        Timer {
            pool: ScheduledThreadPool::fixed_size(capacity),
        }
    }

    /// Returns a `Future` that will be completed in `ms` milliseconds
    pub fn timeout_ms(&self, ms: u32) -> Future<(), ()> {
        let (tx, rx) = Future::pair();
        let pool = self.pool.clone();
        let now = SteadyTime::now();

        tx.receive(move |res| {
            if let Ok(tx) = res {
                let elapsed = (SteadyTime::now() - now).num_milliseconds() as u32;

                if elapsed >= ms {
                    tx.complete(());
                    return;
                }

                pool.schedule_ms(ms - elapsed, move || {
                    tx.complete(());
                });
            }
        });

        rx
    }

    /// Return a `Stream` with values realized every `ms` milliseconds.
    pub fn interval_ms(&self, ms: u32) -> Stream<(), ()> {
        let (tx, rx) = Stream::pair();
        let pool = self.pool.clone();
        let interval = Duration::milliseconds(ms as i64);
        let next = SteadyTime::now() + interval;

        do_interval(pool, tx, next, interval);

        rx
    }
}

/// Processes the interval stream
fn do_interval<S>(pool: ScheduledThreadPool,
                  sender: S,
                  next: SteadyTime,
                  interval: Duration)
        where S: Async<Value=Sender<(), ()>> {

    sender.receive(move |res| {
        if let Ok(sender) = res {
            let now = SteadyTime::now();
            let delay = next - now;
            let next = next + interval;
            let pool2 = pool.clone();

            pool.schedule_ms(delay.num_milliseconds() as u32, move || {
                let busy = sender.send(());
                do_interval(pool2, busy, next, interval);
            });
        }
    });
}

impl Clone for Timer {
    fn clone(&self) -> Timer {
        Timer { pool: self.pool.clone() }
    }
}