Mac上定时运行脚本工具--launchctl

时间:2023-03-09 07:18:17
Mac上定时运行脚本工具--launchctl

在Mac上可以像在Linux上一样,使用crontab来定时运行脚本,但苹果并不推荐这个方法。苹果推荐使用Launchctl来完成定时任务。

首先,我们先写一个可执行的脚本,列子为php脚本,名字为test.php.

其次,要到相对应的目录下面建立plist文件。

一共有5个文件夹,差别在于,Agents文件夹下的plist是需要用户登录后,才会加载的,而Daemons文件夹下得plist是只要开机,可以不用登录就会被加载

Mac上定时运行脚本工具--launchctl

然后,我们编写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>Disabled</key>
<false/>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>com.ryan.test</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/php</string>
<string>/Users/Ryan/Zend/workspaces/DefaultWorkspace/test/test.php</string>
</array>
<key>RunAtLoad</key>
<false/>
<key>StandardErrorPath</key>
<string>/Users/Ryan/Documents/test_log/stderr</string>
<key>StandardOutPath</key>
<string>/Users/Ryan/Documents/test_log/stdout</string>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer></integer>
<key>Minute</key>
<integer></integer>
</dict>
</dict>
</plist>

最后,我们需要load写好的plist文件

launchctl load -w /Library/Daemons/com.ryan.test.plist    // 加载

launchctl unload -w /Library/Daemons/com.ryan.test.plist    // 卸载

参考文档地址:http://launchd.info

工具地址:http://www.soma-zone.com/LaunchControl/