Automating Periodic Scripts With Launchd

22nd May 2016 | Programming

The Goal

Create a recurring maintenance task that will move all screenshots from the Mac's Desktop into a designated folder each day.

The Options

I looked at a number of different options to automate this maintenance task. I needed something non-obtrusive, straightforward and flexible.

The Code

In this example, I created a plist list file named local.cleanupdesktop.plist and placed it into the directory ~/Library/LaunchAgents. This particular plist configuration displays just a small portion of what is possible. In this example, it runs the script cleanupdesktop.sh each day at 9:30. For a more comprehensive list of what options are available, check the comprehensive resources at launchd.info.

The cleanupdesktop.sh script is a small bash script which searches for any screenshots which are on the Desktop and places them into the Screenshots folder. This particular script will take screenshots from the keyboard shortcut or from screenshots taken from the iOS Simulator.

Another Example

The next example is even simpler which has everything contained within the plist file. This launch agent will display an alert every weekday at 5 p.m. (17:00) as a handy reminder. The code passes in program arguments, which effectively invokes an Applescript command: osascript -e 'display notification "Update your tickets" with title "Reminder" sound name "Sosumi"'.

Installing the Launch Agent

To get these new launch agents to run, either log out and then log back in to your account, or the launch agent can be manually loaded from the command line using the launchctl utility:

launchctl load -w ~/Library/LaunchAgents/local.cleanupdesktop.plist

Likewise, if you want to unload the launch agent, use the command:

launchctl unload -w ~/Library/LaunchAgents/local.cleanupdesktop.plist

References