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
//! Timer-based management of operator activators.

use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::time::{Duration, Instant};

use timely::scheduling::activate::Activator;

/// A scheduler allows polling sources to defer triggering their
/// activators, in case they do not have work available. This reduces
/// time spent polling infrequently updated sources and allows us to
/// (optionally) block for input from within the event loop without
/// unnecessarily delaying sources that have run out of fuel during
/// the current step.
#[derive(Default)]
pub struct Scheduler {
    activator_queue: BinaryHeap<TimedActivator>,
}

impl Scheduler {
    /// Creates a new, empty scheduler.
    pub fn new() -> Self {
        Scheduler {
            activator_queue: BinaryHeap::new(),
        }
    }

    /// Returns true whenever an activator is queued and ready to be
    /// scheduled.
    pub fn has_pending(&self) -> bool {
        if let Some(ref timed_activator) = self.activator_queue.peek() {
            Instant::now() <= timed_activator.at
        } else {
            false
        }
    }

    /// Schedule activation at the specified instant. No hard
    /// guarantees on when the activator will actually be triggered.
    pub fn schedule_at(&mut self, at: Instant, activator: Activator) {
        self.activator_queue.push(TimedActivator { at, activator });
    }

    /// Schedule activation after the specified duration. No hard
    /// guarantees on when the activator will actually be triggered.
    pub fn schedule_after(&mut self, after: Duration, activator: Activator) {
        self.activator_queue.push(TimedActivator {
            at: Instant::now() + after,
            activator,
        });
    }
}

impl Iterator for Scheduler {
    type Item = Activator;
    fn next(&mut self) -> Option<Activator> {
        if self.has_pending() {
            Some(self.activator_queue.pop().unwrap().activator)
        } else {
            None
        }
    }
}

struct TimedActivator {
    pub at: Instant,
    pub activator: Activator,
}

// We want the activator_queue to act like a min-heap.
impl Ord for TimedActivator {
    fn cmp(&self, other: &TimedActivator) -> Ordering {
        other.at.cmp(&self.at)
    }
}

impl PartialOrd for TimedActivator {
    fn partial_cmp(&self, other: &TimedActivator) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for TimedActivator {
    fn eq(&self, other: &TimedActivator) -> bool {
        self.at.eq(&other.at)
    }
}

impl Eq for TimedActivator {}