在做ios自动化的过程中,通常离不开mac,需要在mac上开启定时任务。mac下有两种开启定时任务的方式:
- 一种是使用crontab
- 一种是使用Schedule
crontab是linux下的定时任务,在mac os上不推荐使用crontab,倾向于推荐使用Plist的方法。接下来重点介绍一下Plist的使用方法。
1、plist文件的位置
- ~/Library/LaunchAgents :由用户自己定义的任务项
- /Library/LaunchAgents :由管理员为用户定义的任务项
- /Library/LaunchDaemons :由管理员定义的守护进程任务项
- /System/Library/LaunchAgents :由Mac OS X为用户定义的任务项
- /System/Library/LaunchDaemons :由Mac OS X定义的守护进程任务项
2、plist文件编写
先看一个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.haleli.MonkeyRunner.Daemon</string>
<!-- 指定要运行的脚本 -->
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/python</string>
<string>/Users/haleli/Desktop/MonkeyRunner/MonkeyRunner.py</string>
</array>
<!-- 运行间隔 -->
<key>StartInterval</key>
<integer>5</integer>
<!-- 标准输出文件 -->
<key>StandardOutPath</key>
<string>/Users/haleli/Desktop/MonkeyRunner/run.log</string>
<!-- 标准错误输出文件,错误日志 -->
<key>StandardErrorPath</key>
<string>/Users/haleli/Desktop/MonkeyRunner/run.err</string>
</dict>
</plist>
- Label:全局唯一标识
- ProgramArguments:第一个参数为要执行的命令或文件路径,其他参数为传入参数
- StartInterval:设置执行的时间间隔,单位为秒
- StandardOutPath:标准输出文件
- StandardErrorPath:标准错误输出文件,错误日志
从这个简单的任务可以发现,其实plist文件就是一些列的键值对,赋予每个键相应的含义。更多的键值用法可以参考苹果官方文档Launchd-Apple Developer
3、launchctl 的一些命令
// 加载任务
$ launchctl load com.test.task.plist
// 删除任务
$ launchctl unload com.test.task.plist
// 查看任务列表, 使用 grep '任务部分名字' 过滤
$ launchctl list | grep 'com.test.task.plist'
// 开始
$ launchctl start com.test.task.plist
// 停止
$ launchctl stop com.test.task.plist
参考文章
1、https://www.jianshu.com/p/aebaa6a53ca5
2、https://blog.csdn.net/lgt633744/article/details/45932035
3、https://hanks.pub/2016/03/28/mac-launchctl/
4、https://www.cnblogs.com/hanlingzhi/p/6505967.html
5、https://cloud.tencent.com/developer/article/1327501
6、https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html