前言
Linux定时任务crontab定时运行Python脚本,用的是Anaconda3,会出错。
crontab -e
写入* * * * * python ~/a.py
和* * * * * python3 ~/a.py
都出问题。
据说是crontab环境原因,须要指定的Python,改成~/anaconda3/bin/python ~/a.py
后成功。
补充crontab基础
crontab极简示例
- 添加或删除定时任务(edit)
crontab -e
- 以vim模式写入并保存
# 每分钟跑一次
* * * * * echo `pwd` > a.txt
- 查看定时任务列表(list)
crontab -l
- 检测
cat ~/a.txt
部署Python脚本示例
- 创建Python脚本
vi ~/a.py
"""把当前时间写入同名的TXT文件"""
from time import strftime
with open(__file__.replace('py', 'txt'), 'w', encoding='utf-8')as f:
f.write(strftime('%Y-%m-%d %H:%M:%S\n'))
- 添加定时任务
crontab -e
# 每分钟跑一次Python脚本
* * * * * python ~/a.py
- 检测
cat ~/a.txt
crontab+Anaconda示例
- 创建Python脚本
vi ~/a.py
import time, sys
with open(__file__.replace('py', 'txt'), 'w', encoding='utf-8')as f:
f.write(time.strftime('%Y-%m-%d %H:%M:%S\n')) # 当前时间
f.write(sys.version) # Python版本
- 添加定时任务
crontab -e
# 每分钟跑一次Python脚本
* * * * * ~/anaconda3/bin/python ~/a.py
- 检测
cat ~/a.txt
其它
-
首次运行
crontab -e
可能出现select-editor
,可选vim.basic -
每天0点跑一次
0 0 * * * echo `date +"%Y-%m-%d %H:%M:%S"` >> ~/a.txt
- 查看配置信息
cat /etc/crontab
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed