Class: Alarm

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

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Alarm

Returns a new instance of Alarm.



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/alarm.rb', line 5

def initialize config
  config.each do |name, alarm|
    times = Array(alarm[:time])
    days = Array(alarm[:day])
    times.each do |time|
      days.each do |day|
        start day, time, name if alarm[:enabled]
      end
    end
  end
end

Instance Method Details

#start(day, time, name) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/alarm.rb', line 17

def start day, time, name
  Thread.new do
    Kernel.loop do
      d  = Date.parse(day)
      delta = d >= Date.today ? 0 : 7
      d = d + delta

      t = Time.parse(time)

      alarm_time =  DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec, t.zone)

      alarm_time += (alarm_time - DateTime.now) > 0 ? 0 : 7
      sleep_time = ((alarm_time - DateTime.now) * 24 * 60 * 60).to_i

      printf("Alarm '%s' set for %s\n", name, alarm_time.strftime('%a %Y-%m-%d at %H:%M:%S'))
      Kernel.sleep(sleep_time)
      pid = fork{ Kernel.exec 'mpg123','-q', asset('alarm.mp3') }
      Kernel.sleep 5
      Process.kill('QUIT', pid)
    end
  end
end