sno*_*pey 5 launchd node.js osx-mountain-lion macos
我正在尝试在我的 Mac(OSX 10.8.2 Mountain Lion)上每小时运行一个节点脚本。根据排名靠前的搜索结果,最好的方法是添加launchd启动代理。
出于某种原因,它似乎不起作用。
我编写了以下启动代理文件并将其保存为~/Library/LaunchAgents/agenttest.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>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>Label</key>
<string>protocol</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/node</string>
<string>/Users/snorpey/PATH/TO/file.js</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StartInterval</key>
<integer>3600</integer>
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)
我通过launchctl load ~/Library/LaunchAgents/agenttest.plist在终端中运行来启动启动代理。
我还使脚本文件可执行,sudo chmod -x /Users/snorpey/PATH/TO/file.js并使用sudo chmod 777 /Users/snorpey/PATH/TO/file.js.
当我/usr/local/bin/node /Users/snorpey/PATH/TO/file.js在终端中运行时,脚本运行良好。
但是,它在运行时似乎不起作用launchd。我收到以下消息/var/log/system.log:
Jan 15 22:32:46 snorpey com.apple.launchd.peruser.501[595] (agenttest[21625]): Exited with code: 1
Jan 15 22:32:46 snorpey com.apple.launchd.peruser.501[595] (agenttest): Throttling respawn: Will start in 10 seconds
Run Code Online (Sandbox Code Playgroud)
为什么执行脚本失败?
我遇到了一段时间(得到 127 个错误)。事实证明,您的 plist 中需要这样的内容:
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
Run Code Online (Sandbox Code Playgroud)
launchd 似乎以不包含 /usr/local/bin 的最小路径执行事物,节点似乎需要在您的 PATH 上使用它才能正常运行。
事实证明,无论出于何种原因,我都必须以 root 身份运行这项工作。
我将文件移至/Library/LaunchAgents/agenttest.plist.
我还使用 更新了文件所有权sudo chown root /Library/LaunchAgents/agenttest.plist。
以及文件权限sudo chmod 644 /Library/LaunchAgents/agenttest.plist。
以 root 身份运行作业:sudo launchctl load /Library/LaunchAgents/agenttest.plist