Class: Timers::Timer

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/timers.rb

Overview

An individual timer set to fire a given proc at a given time

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timers, interval, recurring = false, &block) ⇒ Timer

Returns a new instance of Timer.



108
109
110
111
112
113
114
# File 'lib/timers.rb', line 108

def initialize(timers, interval, recurring = false, &block)
  @timers, @interval, @recurring = timers, interval, recurring
  @block  = block
  @offset = nil

  reset
end

Instance Attribute Details

#intervalObject (readonly)

Returns the value of attribute interval.



106
107
108
# File 'lib/timers.rb', line 106

def interval
  @interval
end

#offsetObject (readonly)

Returns the value of attribute offset.



106
107
108
# File 'lib/timers.rb', line 106

def offset
  @offset
end

#recurringObject (readonly)

Returns the value of attribute recurring.



106
107
108
# File 'lib/timers.rb', line 106

def recurring
  @recurring
end

Instance Method Details

#<=>(other) ⇒ Object



116
117
118
# File 'lib/timers.rb', line 116

def <=>(other)
  @offset <=> other.offset
end

#cancelObject

Cancel this timer



121
122
123
# File 'lib/timers.rb', line 121

def cancel
  @timers.cancel self
end

#continueObject

Continue this timer



152
153
154
# File 'lib/timers.rb', line 152

def continue
  @timers.continue self
end

#delay(seconds) ⇒ Object

Extend this timer



126
127
128
129
130
# File 'lib/timers.rb', line 126

def delay(seconds)
  @timers.delete self
  @offset += seconds
  @timers.add self
end

#fire(offset = @timers.current_offset) ⇒ Object Also known as: call

Fire the block



140
141
142
143
# File 'lib/timers.rb', line 140

def fire(offset = @timers.current_offset)
  reset(offset) if recurring
  @block.call
end

#inspectObject

Inspect a timer



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/timers.rb', line 157

def inspect
  str = "#<Timers::Timer:#{object_id.to_s(16)} "
  offset = @timers.current_offset

  if @offset
    if @offset >= offset
      str << "fires in #{@offset - offset} seconds"
    else
      str << "fired #{offset - @offset} seconds ago"
    end

    str << ", recurs every #{interval}" if recurring
  else
    str << "dead"
  end

  str << ">"
end

#pauseObject

Pause this timer



147
148
149
# File 'lib/timers.rb', line 147

def pause
  @timers.pause self
end

#reset(offset = @timers.current_offset) ⇒ Object

Reset this timer



133
134
135
136
137
# File 'lib/timers.rb', line 133

def reset(offset = @timers.current_offset)
  @timers.cancel self if @time
  @offset = Float(offset) + @interval
  @timers.add self
end