crontab 在mac上不执行问题研究

44次阅读

共计 1652 个字符,预计需要花费 5 分钟才能阅读完成。

crontab 是个管理定时任务的工具,作用是在特定时间(通过 crontab 的语法配置),自动执行特定任务(想让它执行什么,就写个脚本或 bash 命令)。当你每天都需要执行脚本干一些重复工作的时候,这个东西就派上用场了。
不了解这个东西怎么用的朋友,可以通过点击这里进行一个基本了解。
这篇文章主要是为了记录自己在写 crontab 时踩得一些坑,当我按照顺序做完配置之后,却发现 crontab 中的 task 怎么也跑步起来,于是 google 了一下问题,找到了几个相关 blog,结合在一起验证,终于解决了问题。

crontab 为啥不执行呢?
问了一下谷歌,OS X 的定时任务统统由 launchctl 来管理的,看看 cron 任务有没有在里面
➜ ~ sudo launchctl list | grep cron
208 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
// 这个指令会花费一定时间
一段时间后,创建成功,然后查看
~ 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 是否存在:
<key>KeepAlive</key>
<dict>
<key>PathState</key>
<dict>
<key>/etc/crontab</key>
<true/>
</dict>
</dict>
查看 /etc/crontab 是否存在
➜ ~ ll /etc/crontab
ls: /etc/crontab: No such file or directory
查看得知,该文件不存在,创建该文件。
➜ ~ sudo touch /etc/crontab
最终,就可以成功执行了。
需要注意的是,sh 脚本中的路径,最好使用绝对路径,否则脚本很可能将无法正确执行

正文完
 0