Class: AtDo

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

Constant Summary collapse

VERSION =
"0.6"

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

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/atdo.rb', line 34

def at time, &action
  thread
  raise ArgumentError unless time.kind_of? Time

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

#inspectObject



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

def inspect
  "#<#{self.class}:0x#{self.object_id.to_s(16)} #{@events}>"
end

#stopObject



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

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

#stop!Object



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

def stop!
  @thread.kill if @thread
end

#threadObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/atdo.rb', line 51

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
              # exception handling is left to client code
            end
            @events.shift
          end
        @cvar.wait(*duration)
      end
    end
  end
end

#waitObject



30
31
32
# File 'lib/atdo.rb', line 30

def wait
  @thread.join
end