MAC 开机任务 Launchctl

36 min read

Launchctl

launchctl是一个统一的服务管理框架,启动、停止和管理守护进程、应用程序、进程和脚本

plist文件

launchctl 将根据这个plist文件的信息来启动任务, plist文件使用 xml来定义

<?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>boot-shutdown</string>

<key>ProgramArguments</key>
<array>
  <string>$SCRIPT_PATH/launchdaemon</string>
</array>

<key>RunAtLoad</key>
<true/>

<key>StandardOutPath</key>
<string>$LOG_PATH/boot-shutdown.log</string>

<key>StandardErrorPath</key>
<string>$PLOG_PATH/boot-shutdown.err</string>

</dict>
</plist>

plist文件以键值对的形式存储信息。以上文件的字段解释:

  • Label:标签,也就是运行该plist显示的名字。这里为boot-shutdown
  • ProgramArgumentsarray里可以存放多个需要运行程序。这里的$SCRIPT_PATH请自己修改。
  • RunAtLoad:开机自启,为true
  • StandardOutPath:打印标准输出到某个文件,方便查看程序后台运行的结果,$LOG_PATH自行修改。
  • StandardErrorPath:打印标准错误到某个文件,同上。

plist 存放路径,由用户自己定义的任务项放在这个目录下

~/Library/LaunchAgents

开启删除查看脚本

# 加载任务, -w选项会将plist文件中无效的key覆盖掉,建议加上
launchctl load -w com.denglibing.checkin.plist

# 删除任务
launchctl unload -w com.denglibing.checkin.plist

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

一个 aria2开机运行的例子

IntelliJ IDEA    
<?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>Disabled</key>
	<false/>
	<key>Label</key>
	<string>local.Aria2</string>
	<key>ProgramArguments</key>
	<array>
		<string>bash</string>
		<string>-c</string>
		<string>/usr/local/bin/tmux new -d -s Aria2 '/path/to/shell/Aria2.sh'</string>
	</array>
	<key>RunAtLoad</key>
	<true/>
</dict>
</plist>

一个开机运行mongodb的例子

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>EnvironmentVariables</key>
    <dict>
      <key>PATH</key>
      <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:</string>
    </dict>
    <key>Label</key>
    <string>com.startup.mongodb</string>
    <key>ProgramArguments</key>
    <array>
    <string>/Users/bejond/startmongodb.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
    <key>LaunchOnlyOnce</key>        
    <true/>
    <key>StandardErrorPath</key>
    <string>/tmp/startup.mongodb.stderr</string>
    <key>UserName</key>
    <string>bejond</string>
    <key>GroupName</key>
    <string>admin</string>
    <key>InitGroups</key>
    <true/>
  </dict>
</plist>	

plist 以root 方式来运行

cd /Library/LaunchAgents/
sudo chown root:wheel com.papercut.client.plist
sudo chmod 644 com.papercut.client.plist
sudo spctl --master-disable
xattr -cr /Applications/PCClient.app
sudo chmod -R 755 /Applications/PCClient.app
sudo xattr -dr com.apple.quarantine /Applications/PCClient.app

https://bytenote.net/article/124239673718472705