Last active
August 29, 2015 14:08
-
-
Save redcapital/b8203ba7ed399a74af76 to your computer and use it in GitHub Desktop.
Simple countdown timer script for Mac OS X
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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