Class: AtDo

Inherits:
Object
  • Object
show all
Defined in:
lib/atdo.rb

Constant Summary collapse

VERSION =
"0.4"

Instance Method Summary collapse

Constructor Details

#initialize(storage: Array) ⇒ AtDo

Storage classes known to work: Array (default), MultiRBTree.



7
8
9
10
11
12
13
14
# File 'lib/atdo.rb', line 7

def initialize storage: Array
  @storage_class = storage
  @events = storage.new
  @sorted = !defined?(@events.reverse)
  @mon = Monitor.new
  @cvar = @mon.new_cond
  @thread = nil
end

Instance Method Details

#at(time, &action) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/atdo.rb', line 26

def at time, &action
  thread
  @mon.synchronize do
    if @sorted
      @events[time] = action
      t, _ = @events.first
    else
      @events << [time, action]
      t, _ = @events.sort_by! {|t, a| t}.first
    end
    @cvar.signal if t == time
  end
  self
end

#stopObject



16
17
18
19
20
# File 'lib/atdo.rb', line 16

def stop
  @mon.synchronize do
    @thread.kill if @thread
  end
end

#stop!Object



22
23
24
# File 'lib/atdo.rb', line 22

def stop!
  @thread.kill if @thread
end

#threadObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/atdo.rb', line 41

def thread
  @thread ||= Thread.new do
    @mon.synchronize do
      loop do
        duration =
          loop do
            t, a = @events.first
            break nil if !t
            t_now = Time.now
            break t-t_now if t > t_now
            begin
              a.call
            rescue => ex
              # exception handling is left to client code
            end
            @events.shift
          end
        @cvar.wait *duration
      end
    end
  end
end