Skip to content

Instantly share code, notes, and snippets.

@mcculley
Last active November 18, 2022 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcculley/62704c36351fd5d8f67c5299a245279e to your computer and use it in GitHub Desktop.
Save mcculley/62704c36351fd5d8f67c5299a245279e to your computer and use it in GitHub Desktop.
#!/bin/bash
# This is a tool to control contactsd on macOS. For some reason, contactsd
# consumes a lot of CPU when running against my (large, 9,779 entry)
# addressbook. I think contactsd is responsible for synchronizing the
# addressbook in the background, but it makes my local instance of the Contacts
# app hang and burns up my battery. So I stop contactsd when I use the Contacts
# app and then restart it to allow the sync to happen. However, modern macOS
# will not allow one to disable the contactsd launch agent. System Integrity
# Protection will also not allow one to disable it. So what I really do is
# send the process a SIGSTOP signal to make it hang. Then I just restart it
# when I really want to start it.
contactsd_status=normal
while true
do
foreground=$(osascript -e 'tell application "System Events"' -e 'set frontApp to name of first application process whose frontmost is true' -e 'end tell')
if [ $foreground = "Contacts" ]
then
echo "Contacts is in the foreground."
if [ $contactsd_status = "normal" ]
then
echo "Pausing contactsd."
# Get the PID of the running contactds process
CPID=$(launchctl list | grep com.apple.contactsd | cut -d$'\t' -f1)
if [ $CPID != "-" ]
then
# Send a SIGSTOP to the process to pause it. If we kill it, launchd will
# just restart it.
kill -SIGSTOP $CPID
contactsd_status=paused
fi
fi
else
echo "Contacts is not in the foreground."
if [ $contactsd_status = "paused" ]
then
echo "Restarting contactsd."
launchctl stop com.apple.contactsd && launchctl start com.apple.contactsd
contactsd_status=normal
fi
fi
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment