Class: Timer

Inherits:
Object show all
Includes:
Observable
Defined in:
lib/infra/timer.rb

Direct Known Subclasses

PeriodicTimer

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(interval, observer = nil, &block) ⇒ Timer

Returns a new instance of Timer.



40
41
42
43
44
45
# File 'lib/infra/timer.rb', line 40

def initialize interval, observer=nil, &block
  @interval = interval
  @code = block if block
  add_observer observer if observer
  @_timer_thread_ = nil
end

Class Method Details

.start(interval, observer = nil, &block) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/infra/timer.rb', line 30

def start interval, observer=nil, &block
  timer = if block
    new interval, observer, &block
  else
    new interval, observer
  end
  timer.start
end

Instance Method Details

#cancelObject Also known as: stop



59
60
61
62
63
64
# File 'lib/infra/timer.rb', line 59

def cancel
  return unless @_timer_thread_
  [:exit, :join].each { |x| @_timer_thread_.send x }
  changed and notify_observers(:ev_timer_cancel, id, Time.now.strftime("%M:%S"))
  yield if block_given?
end

#reset(&block) ⇒ Object



71
72
73
74
# File 'lib/infra/timer.rb', line 71

def reset &block
  cancel
  start(&block)
end

#running?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/infra/timer.rb', line 67

def running?
  @_timer_thread_ and @_timer_thread_.alive?
end

#start(_interval = @interval, &block) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/infra/timer.rb', line 47

def start _interval=@interval, &block
  stop if running?
  changed and notify_observers(:ev_timer_start, id, Time.now.strftime("%M:%S"))
  _code = block || @code
  @_timer_thread_ = Thread.new(_interval, _code) do |interval, code|
    sleep(interval)
    code.call if code
    changed and notify_observers(:ev_timer_fire, id, Time.now.strftime("%M:%S"))
  end
  self
end