Recently, I’ve been traveling quite a bit, which means spending time away from a sleep environment that I’ve become accustom too. At night, when I first go to bed, I like to listen to the radio for an hour or so on a sleep timer, but while on the road I don’t usually have that option. In order to fix the problem, I whipped up a quick BASH shell script to pause iTunes after a preset amount of time. If no time parameter is passed, it defaults to 60 mins.
Download: itunes_sleep_timer.sh
#!/bin/bash
itunes_grep_string="/Applications/iTunes.app/Contents/MacOS/"
time_to_close=60 #Minutes
if [ ! -z $1 ]; then
time_to_close=$1
fi
itunes_pid=`ps aux | grep -i "$itunes_grep_string" | grep -v grep | awk '{print $2}'`
elapsed_minutes=0
if [ "$itunes_pid" == "" ]; then
echo "iTunes is not currently running"
exit 1;
fi
echo "iTunes pid is: $itunes_pid"
echo "iTunes will pause in $time_to_close minutes"
while [ $elapsed_minutes -lt $time_to_close ]; do
printf "`expr $time_to_close - $elapsed_minutes` minutes remaining\\r"
sleep 60
elapsed_minutes=`expr $elapsed_minutes + 1`
done
osascript -e 'tell application "iTunes"' -e "pause" -e "end tell"
UPDATE: October, 4th, 2007
By request (and request, I mean the lame-asses that email me instead of posting a comment), I’ve added a ruby version of this script. It’s the same number of lines, so I’m not sure what benefit your receiving other than being able to verify that the time parameter is an integer.
Download: itunes_sleep_timer.rb
#!/usr/bin/env ruby
itunes_grep_string = "/Applications/iTunes.app/Contents/MacOS/"
time_to_close = 60 #Minutes
if ARGV[0].to_i != 0
time_to_close = ARGV[0].to_i
end
itunes_pid = `ps aux | grep -i "#{itunes_grep_string}" | grep -v grep | awk '{print $2}'`
elapsed_minutes = 0
if itunes_pid == ""
STDERR.puts "iTunes is not currently running"
exit 1
end
puts "iTunes pid is: #{itunes_pid}"
puts "iTunes will pause in #{time_to_close} minutes"
while elapsed_minutes < time_to_close
printf("%s minutes remaining\\n", time_to_close - elapsed_minutes)
sleep(60)
elapsed_minutes = elapsed_minutes + 1
end
`osascript -e 'tell application "iTunes"' -e "pause" -e "end tell"`