Class: AtDo

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

Constant Summary collapse

VERSION =
"0.5"

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
15
# 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
  @t0 = Time.now
end

Instance Method Details

#at(time, &action) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/atdo.rb', line 31

def at time, &action
  thread
  time < @t0
  @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



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

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

#stop!Object



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

def stop!
  @thread.kill if @thread
end

#threadObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/atdo.rb', line 47

def thread
  @thread ||= Thread.new do
    Thread.current.abort_on_exception = true
    @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

#waitObject



27
28
29
# File 'lib/atdo.rb', line 27

def wait
  @thread.join
end