此文章发布于36
个月前,部分信息可能已经过时
,请自行斟酌确认。
macOS
下的 crontab
定时任务和 Linux
略有不同,它是由 launchctl
来管理的。
首先查看服务是否运行
sudo launchctl list | grep cron
#输出
12180 0 com.vix.cron
#或者
- 0 com.vix.cron
创建启动项的配置:
locate com.vix.cron
WARNING: The locate database (/var/db/locate.database) does not exist.
To create the database, run the following command:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
Please be aware that the database can take some time to generate; once
the database has been created, this message will no longer appear.
第一次使用会提示 database
不存在,按照提示步骤创建一个:
# 执行这个命令后要等一会儿,过个几分钟
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
过一段时间后查看配置项
locate com.vix.cron
# 如果输出 /System/Library/LaunchDaemons/com.vix.cron.plist 表示启动项已配置好了。
#查看
cat /System/Library/LaunchDaemons/com.vix.cron.plist
#输出
<?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>Label</key>
<string>com.vix.cron</string>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/cron</string>
</array>
<key>KeepAlive</key>
<dict>
<key>PathState</key>
<dict>
<key>/etc/crontab</key>
<true/>
</dict>
</dict>
<key>QueueDirectories</key>
<array>
<string>/usr/lib/cron/tabs</string>
</array>
<key>EnableTransactions</key>
<true/>
</dict>
</plist>
注意里面有个 keepAlive
的条件是 /etc/crontab
是否存在
配置 crontab
检查 /etc/crontab
文件是否存在,如果不存在则创建
sudo touch /etc/crontab
这些都检查完之后就可以通过 crontab -e
创建任务了。
crontab -e
# 每分钟执行一次将当前时间写入桌面 cron.txt
* * * * * /bin/date >> /Users/xinggang/Desktop/cron.txt
注意脚本路径/添加环境变量
需要注意的是,sh
脚本中的路径,最好使用绝对路径,否则脚本很可能将无法正确执行,因为自己配置的环境变量可能读不到。
我们手动执行某个脚本时,是在当前 shell
环境下进行的,程序能找到环境变量;
而系统自动执行任务调度时,除了默认的环境,是不会加载任何其他环境变量的。
因此就需要在 crontab
文件中指定任务运行所需的所有环境变量。
#! /bin/sh
source /etc/profile #添加这句
//其他脚本
定时任务不执行
测试是否是环境变量问题,配置了 php cron
定时任务不执行,通过下面的任务发现最后生成的 xxx.txt
是没有内容的,而 zzz.txt
有内容,说明是环境变量问题。
* * * * * php -m >> /Users/xinggang/Desktop/xxx.txt
* * * * * /usr/local/opt/php@7.4/bin/php -m >> /Users/xinggang/Desktop/zzz.txt
macOS 10.15+ 授权磁盘访问权限:
在 macOS 10.15 Catalina
以上的系统上,由于权限升级,还需要给 cron
添加完全磁盘访问权限,不然定时任务还是无法执行。
具体方法,先打开系统偏好设置->隐私->完全磁盘访问权限
,左下角解锁。然后打开 Finder
,菜单栏前往->前往文件夹
,输入 /usr/sbin
,找到 cron
,把它拖到完全磁盘访问权限的列表中。
或者使用命令打开
# cron 程序所在目录:
whereis cron
输出:/usr/sbin/cron
# 打开目录
open /usr/sbin
代码示例
# 每隔一分钟输入当前时间到桌面文件
* * * * * /bin/date >> /Users/xinggang/Desktop/cronnnn.txt