Skip to content

Instantly share code, notes, and snippets.

@redcapital
Last active Aug 29, 2015
Embed
What would you like to do?
Simple countdown timer script for Mac OS X
#!/usr/bin/env ruby
if ARGV.empty?
puts 'Usage: timer TIME'
exit
end
TOKENS = { 's' => 1, 'm' => 60, 'h' => 60 * 60 }
def parse_duration(str)
time = 0
str.scan(/(\d+)(\w)/).each do |amount, measure|
time += amount.to_i * TOKENS[measure] if TOKENS.has_key?(measure)
end
return time
end
def format_duration(seconds)
minutes = seconds / 60
seconds = seconds % 60
parts = []
if minutes > 0
parts << "#{minutes} minutes"
end
if seconds > 0
parts << "#{seconds} seconds"
end
return parts.join(', ')
end
def notify(message)
system 'osascript', '-e', %[display notification "#{message}" sound name "Ping" with title "Timer"]
end
duration = parse_duration(ARGV.join(' '))
if duration.zero?
puts 'Specify duration'
exit 1
end
# Notify when 5% of time is left
wake_time = (duration * 0.05).ceil
if wake_time < duration
sleep duration - wake_time
notify(format_duration(wake_time) + ' remaining')
end
# Sleep remaining time
sleep wake_time
notify 'Time is up'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment