intro

launchctl是一个统一的服务管理框架,可以启动、停止和管理守护进程、应用程序、进程和脚本等。 launchctl是通过配置文件来指定执行周期和任务的。

launchctl 将根据plist文件的信息来启动任务。

Plist 脚本目录地址:

  • ~/Library/LaunchAgents 由用户自己定义的任务项

  • /Library/LaunchAgents 由管理员为用户定义的任务项

  • /Library/LaunchDaemons 由管理员定义的守护进程任务项

  • /System/Library/LaunchAgents 由Mac OS X为用户定义的任务项

  • /System/Library/LaunchDaemons 由Mac OS X定义的守护进程任务项

区别

/System/Library和/Library和~/Library目录的区别

  • /System/Library目录是存放Apple自己开发的软件。
  • /Library目录是系统管理员存放的第三方软件。
  • ~/Library/是用户自己存放的第三方软件。

LaunchDaemons和LaunchAgents的区别

  • LaunchDaemons是用户未登陆前就启动的服务(守护进程)。
  • LaunchAgents是用户登陆后启动的服务(守护进程)。

plist文件结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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>
<!-- Label唯一的标识 -->
<key>Label</key>
<string>com.demo.plist</string>
<!-- 指定要运行的脚本 -->
<key>ProgramArguments</key>
<array>
<string>/Users/demo/run.sh</string>
</array>
<!-- 指定要运行的时间 -->
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>00</integer>
<key>Hour</key>
<integer>22</integer>
</dict>
<!-- 标准输出文件 -->
<key>StandardOutPath</key>
<string>/Users/demo/run.log</string>
<!-- 标准错误输出文件,错误日志 -->
<key>StandardErrorPath</key>
<string>/Users/demo/run.err</string>
</dict>
</plist>

命令和参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 加载任务, -w选项会将plist文件中无效的key覆盖掉,建议加上
$ launchctl load -w com.demo.plist

# 删除任务
$ launchctl unload -w com.demo.plist

# 查看任务列表, 使用 grep '任务部分名字' 过滤
$ launchctl list | grep 'com.demo'

# 开始任务
$ launchctl start com.demo.plist

# 结束任务
$ launchctl stop com.demo.plist