Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Track sleep of the computer with Mac OSX agent config for autoload
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">
# run this to load the agent
launchctl load ~/Library/LaunchAgents/ilya.track_sleep.plist
# run this to unload the agent and stop the process
launchctl unload ~/Library/LaunchAgents/ilya.track_sleep.plist
# to apply config change, must unload and load
#!/usr/bin/env ruby
def log(str)
# will always create log file in current working directory
open('track_sleep.log','a'){|f| f.puts str }
log "*** #{now.strftime("%Y-%m-%d %a %H:%M:%S")}: Started"
while true
now, past =, now
diff = (now-past).to_i
if diff>15*60
prev, last = last, now
log "Work: #{prev.strftime("%Y-%m-%d %a %H:%M")} -> #{past.strftime("%H:%M")}" if prev && past>prev &&
# this part might be important in case of progam restart, when it won't have previous time
log "Sleep: #{past.strftime("%Y-%m-%d %a %H:%M:%S")} -> #{now.strftime("%Y-%m-%d %a %H:%M:%S")} (#{diff/3600}:#{(diff%3600)/60}:#{diff%60})"
sleep 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment