Skip to content

Instantly share code, notes, and snippets.

@redcapital
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redcapital/b8203ba7ed399a74af76 to your computer and use it in GitHub Desktop.
Save redcapital/b8203ba7ed399a74af76 to your computer and use it in GitHub Desktop.
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