Use Launchd to manage and execute routine tasks on Mac OS X

Jan 5, 2016 Mac 中文版

Launchd is designed to manage processes, applications and scripts, and it also provides the same services as cron provides. This post is about how to use Launchd to manage and execute your routine jobs on Mac OS X.



Understand Launchd

Launchd manages things via many well-defined Property Lists ( e.g., XYZ.plist ), which include detailed information about programs or tasks. And there are different directories for users to store them. Let’s take a look about where you should put your plist files:

~/Library/LaunchAgents           Agents provided by the user.
 /Library/LaunchAgents           Agents provided by the administrator.
 /Library/LaunchDaemons          System daemons provided by the administrator.
 /System/Library/LaunchAgents    Agents provided by Apple.
 /System/Library/LaunchDaemons   System daemons provided by Apple.

For most users, it’s not necessary to create or modify anything in those directories whose name starts with /System. In most cases, we just create plist files and put them in other directories. What’s more, there is an useful tool called Launchctl for us to manipulate Launchd.

Create the task definition

For example, I want to run a shell script at 14:30 everyday. Let’s create the plist file, and make the file’s name like this: com.myname.launch.some.program.plist.

Once created the plist file, I put it in ~/Library/LaunchAgents because this task is for myself not for all users or the system.


Use Launchctl

Now, we can load the task by using Launchctl. Here are some useful commands:

# Load task
launchctl load ~/Library/LaunchAgents/com.myname.launch.some.program.plist

# Remove task
launchctl unload ~/Library/LaunchAgents/com.myname.launch.some.program.plist

# Manually execute task
launchctl start com.myname.launch.some.program

# List all tasks
launchctl list

When using the command launchctl list, you can notice that there is a column named “status”. If the status code is not 0, it might some errors occur. To get information about status code, you can use launchctl error [code].


You might also like:




If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.