Class: Sleeper::Timer

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

Overview

TODO: StateMachine? TODO: Need to be able to add and remove schedules?

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schedule, opts = {}) ⇒ Timer

Returns a new instance of Timer.



7
8
9
10
11
12
# File 'lib/sleeper/timer.rb', line 7

def initialize(schedule, opts={})
  @cyclic = opts[:cyclic] || false
  @default = opts[:default] || nil
  from_hash(schedule) if schedule.class == Hash
  from_array(schedule) if schedule.class == Array
end

Instance Attribute Details

#defaultObject

Returns the value of attribute default.



5
6
7
# File 'lib/sleeper/timer.rb', line 5

def default
  @default
end

#scheduleObject (readonly)

Returns the value of attribute schedule.



5
6
7
# File 'lib/sleeper/timer.rb', line 5

def schedule
  @schedule
end

Instance Method Details

#follow_schedule(schedule) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/sleeper/timer.rb', line 21

def follow_schedule(schedule)
  period = schedule.current

  sleep(period)
  schedule.next

  period
end

#reset(key = nil) ⇒ Object

TODO: Hash reset should be separate method and should handle entire hash or specific keys.



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/sleeper/timer.rb', line 31

def reset(key=nil)
  return @schedule[key].reset unless key.nil?

  if @schedule.class == Hash
    @schedule.values.each do |schedule|
      schedule.reset
    end
  else
    @schedule.reset
  end
  #key.nil? ? @schedule.reset : @schedule[key].reset
end

#run(&block) ⇒ Object



14
15
16
17
18
19
# File 'lib/sleeper/timer.rb', line 14

def run(&block)
  block_given? ? schedule = @schedule[block.call] : schedule = @schedule
  
  # TODO: If schedule nil then use default or raise exception?
  follow_schedule(schedule)
end