Example: Writing a Launch Agent for Apple's launchd

Clutter in programmer workspaces, whether digital or physical, add a mental cost. An area of common clutter is the ~/Downloads directory in Mac OS X. I want to clean it up… programmatically.

The Goal

I want a background job to find files in ~/Downloads which haven’t been modified within the past week and move them into ~/.Trash. In zsh, we do:

mv ~/Downloads/*(mw+1) ~/.Trash

Read man zshexpn for more awesomeness on shell expansion.

Launch Agents

For a user-specific background job, Apple recomends creating a Launch Agent, which is a .plist XML file located in ~/Library/LaunchAgents.

~/Library/LaunchAgents/com.thoughtbot.cleandownloads.plist will run my script once an hour:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.thoughtbot.cleandownloads</string>
  <key>ProgramArguments</key>
  <array>
    <string>mv</string>
    <string>~/Downloads/*(mw+1) ~/.Trash</string>
  </array>
  <key>StartCalendarInterval</key>
  <dict>
    <key>Hour</key>
    <integer>1</integer>
  </dict>
</dict>
</plist>

Read Creating Launch Daemons and Agents for more on how to structure the .plist file.

Hound automatically reviews Ruby, JavaScript, and CoffeeScript code in your GitHub pull requests and comments on style violations. It is free for open source repos and $12/month per private repo.