I tend to go to sleep while watching movies or TV shows on my computer. I didn’t know of any other way to set your computer to sleep after a given time, so I wrote up a small applescript to do this for me. I thought since I’ve learned so much from MacScripter, I’d give back to the community, so here it is. The input supports a number of different formats, e.g. “1 hour 30 minutes”, “2 h 45 m”, “23 seconds”, etc. Save it as a stay open application.
set sleepTime to 0 set theText to text returned of (display dialog "Set sleep timer for:" default answer "1 hour 30 minutes") set defaults to AppleScript's text item delimiters set AppleScript's text item delimiters to " " -- use " " as delimiters set theWords to text items of theText set timesToRun to (number of theWords) / 2 set n to 0 -- index -- parse time. repeat timesToRun times set n to n + 1 set tempTime to item n of theWords as integer set n to n + 1 set tempWord to item n of theWords if tempWord contains "h" then -- hours set sleepTime to sleepTime + tempTime * 3600 else if tempWord contains "m" then -- minutes set sleepTime to sleepTime + tempTime * 60 else -- seconds set sleepTime to sleepTime + tempTime end if end repeat set AppleScript's text item delimiters to defaults -- restore default delimiters delay sleepTime tell application "System Events" sleep end tell