crontab 解决 mac 下通过 crontab 设置了 Python 脚本的定时任务却无法运行

背景

通过 crontab 定时运行 python 脚本来发送钉钉消息

https://www.cnblogs.com/poloyy/p/15565875.html

一开始的定时任务

*/1 * * * * python3 /Users/test.py

确定 Python 脚本是否可正常执行

命令行下敲

 python3 /Users/test.py

发现是可以正常运行的

那为什么 crontab 不运行呢?来一步步解决!

OS X 的定时任务统统由 launchctl 来管理的,看看 cron 任务有没有在里面

# 定时任务统统由 launchctl 来管理的,看看 cron 任务有没有在里面
sudo launchctl list | grep cron 

# 有记录。查看一下启动项的配置
locate com.vix.cron

# 创建一个database
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist

# 查看 /etc/crontab 是否存在
ls -alF /etc/crontab

# 创建该文件
sudo touch /etc/crontab

以为搞定了!结果一分钟后还是不行

验证 crontab 是否可真正执行

# 每分钟输出当前时间到time.txt上.
*/1 * * * * /bin/date >> /User/time.txt 

一分钟后去看,发现是有文件的,证明 crontab 没问题

关键点:绝对路径

一开始写的定时任务中,python3 是相对路径,这是不对的,应该用绝对路径

*/1 * * * * /usr/local/opt/python@3.9/bin/python3.9 /User/test.py

这样就可以正常执行了!

原文地址:https://www.cnblogs.com/poloyy/p/15565916.html