参考文档:
Mac设置开机启动
Mac中的定时任务利器:launchctl
Mac--Launchctl介绍
launchctl 是什么?
控制 macos 系统的启动程序,可以用来控制服务的自动启动或者关闭,类似于 linux 的 systemctl。
plist 是什么
文件类型,在 mac 中类似于 linux 的 desktop 文件。
一般放置在这几个地方
~/Library/LaunchAgents 由用户自己定义的任务项, 我们使用这个即可
/Library/LaunchAgents 由管理员为用户定义的任务项
/Library/LaunchDaemons 由管理员定义的守护进程任务项
/System/Library/LaunchAgents 由Mac OS X为用户定义的任务项
/System/Library/LaunchDaemons 由Mac OS X定义的守护进程任务项
plist 目录结构
通过命令
man launchd.plist
可以查看 plist 的语法。
<?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>
<string>start</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>
加载命令
# 加载任务, -w 可以让 disable 的服务变成 enable 状态
$ launchctl load -w com.demo.plist
# 删除任务
$ launchctl unload -w com.demo.plist
# 查看任务列表
$ launchctl list