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.



71
72
73
74
75
76
77
# File 'lib/timers.rb', line 71

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

  reset
end

Instance Attribute Details

#intervalObject (readonly)

Returns the value of attribute interval.



69
70
71
# File 'lib/timers.rb', line 69

def interval
  @interval
end

#recurringObject (readonly)

Returns the value of attribute recurring.



69
70
71
# File 'lib/timers.rb', line 69

def recurring
  @recurring
end

#timeObject (readonly)

Returns the value of attribute time.



69
70
71
# File 'lib/timers.rb', line 69

def time
  @time
end

Instance Method Details

#<=>(other) ⇒ Object



79
80
81
# File 'lib/timers.rb', line 79

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

#cancelObject

Cancel this timer



84
85
86
# File 'lib/timers.rb', line 84

def cancel
  @timers.cancel self
end

#fire(now = Time.now) ⇒ Object Also known as: call

Fire the block



96
97
98
99
# File 'lib/timers.rb', line 96

def fire(now = Time.now)
  reset(now) if recurring
  @block.call
end

#inspectObject

Inspect a timer



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/timers.rb', line 103

def inspect
  str = "#<Timers::Timer:#{object_id.to_s(16)} "
  now = Time.now

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

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

  str << ">"
end

#reset(now = Time.now) ⇒ Object

Reset this timer



89
90
91
92
93
# File 'lib/timers.rb', line 89

def reset(now = Time.now)
  @timers.cancel self if @time
  @time = now + @interval
  @timers.add self
end