Automatically quit Papers (or any app) after long idle time

Alec Jacobson

August 09, 2013

weblog/

I use the Papers app to organize my academic papers and Dropbox to "sync" Papers' Library between my home and work computers. Only Papers will freak out if I try to open it on both computers. Papers: your library is currently in use. If I have access to Internet then I can just remote desktop or ssh into the other computer and quit papers. But if I'm offline then I'm locked out of Papers or I run the risk of screwing up its database. To solve this I wrote a little script that I run every five minutes. It checks if the computer is idle for a while then shuts down Papers. Save this in a file called quit_app_on_idle.app:

on run argv
  set app_name to item 1 of argv
  set min_idle to ((item 2 of argv) as number)
  -- Idle time in seconds
  -- http://macscripter.net/viewtopic.php?pid=144392
  set idle_time to ((do shell script "/usr/sbin/ioreg -c IOHIDSystem | /usr/bin/awk '/HIDIdleTime/ {print int($NF/1000000000); exit}'") as number)

  if idle_time >= min_idle then
    -- quit Papers if running
    -- http://macscripter.net/viewtopic.php?id=4396

    tell application "System Events" to set processExists to exists process app_name

    if processExists then
      tell application app_name
        quit
      end tell
    end if
  end if
end run

Then set up a cronjob to run this every 5 minutes checking for 30 minutes (1800 seconds) of idle time before closing Papers.

*/5 * * * * osascript /usr/local/bin/quit_app_on_idle.scpt Papers2 1800