Automating cleanup on my Mac (launchd)

In my daily online social travels, I sometimes need to download images, scripts, and more than have a real shelf life. I have a Temp Items folder on my Mac Desktop where I save all this stuff. I could clean the files up after I make an X post, etc. but I don’t need to think about it. Why? launchd.

Using Terminal on the Mac, you can run this bash.

mkdir -p ~/Library/LaunchAgents
nano ~/Library/LaunchAgents/com.user.foldercleanup.plist

Then use this XML for the plist created. Make sure to change all the paths and strings to serve you best.

<?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.user.foldercleanup</string>
    <key>StartInterval</key>
    <integer>604800</integer> <!-- 604800 seconds = 1 week -->
    <key>ProgramArguments</key>
    <array>
      <string>/bin/bash</string>
      <string>-c</string>
      <string>rm -rf /path/to/folder/*</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
  </dict>
</plist>

Now load the job

launchctl load ~/Library/LaunchAgents/com.user.foldercleanup.plist

So you can see that this will schedule a run for 1 week to clear out the folder you chose. This is a more modern approach than using a cron job – although you can find GUI for cron which is a nice thing. Oh wait, there is launch control which provides a GUI for it.

If you want to stop the scheduled execution, you can use

launchctl unload ~/Library/LaunchAgents/com.user.foldercleanup.plist

and then schedule it again by using

launchctl load ~/Library/LaunchAgents/com.user.foldercleanup.plist

If you want to remove it altogether

launchctl unload ~/Library/LaunchAgents/com.user.foldercleanup.plist
#Then to remove it - remember to use paths to your liking
rm ~/Library/LaunchAgents/com.user.foldercleanup.plist

To check if it’s running after, try this. If nothing appears,. it’s gonzo.

launchctl list | grep com.user.foldercleanup

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.