Class: Timer
Direct Known Subclasses
Class Method Summary collapse
Instance Method Summary collapse
- #cancel ⇒ Object (also: #stop)
-
#initialize(interval, observer = nil, &block) ⇒ Timer
constructor
A new instance of Timer.
- #reset(&block) ⇒ Object
- #running? ⇒ Boolean
- #start(_interval = @interval, &block) ⇒ Object
Constructor Details
#initialize(interval, observer = nil, &block) ⇒ Timer
Returns a new instance of Timer.
40 41 42 43 44 |
# File 'lib/infra/timer.rb', line 40 def initialize interval, observer=nil, &block @interval = interval @code = block if block add_observer observer if observer 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
#cancel ⇒ Object Also known as: stop
58 59 60 61 62 63 |
# File 'lib/infra/timer.rb', line 58 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
70 71 72 73 |
# File 'lib/infra/timer.rb', line 70 def reset &block cancel start &block end |
#running? ⇒ Boolean
66 67 68 |
# File 'lib/infra/timer.rb', line 66 def running? @_timer_thread_ and @_timer_thread_.alive? end |
#start(_interval = @interval, &block) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/infra/timer.rb', line 46 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 |