Debian Codegraph @

ruby/lib/util/schedule.rb

raw
1 # Licensed to the Apache Software Foundation (ASF) under one
2 # or more contributor license agreements. See the NOTICE file
3 # distributed with this work for additional information
4 # regarding copyright ownership. The ASF licenses this file
5 # to you under the Apache License, Version 2.0 (the
6 # "License"); you may not use this file except in compliance
7 # with the License. You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing,
12 # software distributed under the License is distributed on an
13 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 # KIND, either express or implied. See the License for the
15 # specific language governing permissions and limitations
16 # under the License.
17
18 module Qpid::Proton
19
20 # @private
21 module TimeCompare
22 # t1 <= t2, where nil is treated as "distant future"
23 def before_eq(t1, t2) (t1 && t2) ? (t1 <= t2) : t1; end
24
25 # min(t1, t2) where nil is treated as "distant future"
26 def earliest(t1, t2) before_eq(t1, t2) ? t1 : t2; end
27 end
28
29 # @private
30 # A time-sorted list of objects. Thread unsafe.
31 class Schedule
32 include TimeCompare
33 Entry = Struct.new(:time, :item)
34
35 def initialize() @entries = []; end
36
37 def empty?() @entries.empty?; end
38
39 def next_tick()
40 @entries.first.time unless @entries.empty?
41 end
42
43 # @param at [Time] Insert item at time +at+
44 # @param at [Numeric] Insert item at +Time.now \+ at+
45 # @param at [0] Insert item at Time.at(0)
46 def insert(at, item)
47 time = case at
48 when 0 then Time.at(0) # Avoid call to Time.now for immediate tasks
49 when Numeric then Time.now + at
50 else at
51 end
52 index = time && (([email protected]).bsearch { |i| @entries[i].time > time })
53 @entries.insert(index || -1, Entry.new(time, item))
54 end
55
56 # Return next item due at or before time, else nil
57 def pop(time)
58 @entries.shift.item if [email protected]? && before_eq(@entries.first.time, time)
59 end
60
61 def clear() @entries.clear; end
62 end
63 end