Class: TimeEgg

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(trigger_frequency: 1.hour, sleep_time: 15.minutes) ⇒ TimeEgg

Returns a new instance of TimeEgg.



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

def initialize(trigger_frequency: 1.hour, sleep_time: 15.minutes)
  raise ArgumentError "trigger_frequency can't be less than sleep_time" if trigger_frequency < sleep_time

  raise ArgumentError "minimum sleep_time is 1 second" if sleep_time < 1

  @trigger_frequency = trigger_frequency
  @sleep_time = sleep_time
end

Instance Attribute Details

#sleep_timeObject (readonly)

Returns the value of attribute sleep_time.



19
20
21
# File 'lib/time_egg.rb', line 19

def sleep_time
  @sleep_time
end

#trigger_frequencyObject (readonly)

Returns the value of attribute trigger_frequency.



19
20
21
# File 'lib/time_egg.rb', line 19

def trigger_frequency
  @trigger_frequency
end

Instance Method Details

#timestampObject



30
31
32
# File 'lib/time_egg.rb', line 30

def timestamp
  "#{Time.now.strftime("%H:%M:%S")}"
end

#trigger(&block) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/time_egg.rb', line 34

def trigger(&block)
  trigger_time = Time.now
  next_trigger_check = Time.now

  while true
    if Time.now >= trigger_time
      begin
        execution_quote = CharactersQuotes.execution_quotes
        puts "#{timestamp}: #{execution_quote[:start]}"
        block.call
        puts "#{timestamp}: #{execution_quote[:finish]}"
      rescue Exception => error
        puts "#{timestamp}: #{execution_quote[:failure].(error)}"
      ensure
        trigger_time = Time.now + trigger_frequency
        next_trigger_check = Time.now + sleep_time
        puts "#{timestamp}: #{CharactersQuotes.next_trigger_quote(trigger_time)}"
      end
    elsif Time.now >= next_trigger_check
      puts "#{timestamp}: #{CharactersQuotes.sleep_quote}"
      next_trigger_check = Time.now + sleep_time
    end
    sleep(1)
  end
end