小道尔,网上各种教程。
添加新一行
格式为:分 时 日 月 星期几 [命令]
*号表示every
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
59 23 * * * /home/qq/anaconda3/bin/python /home/qq/test.py
这个编辑器比较神奇,ctrl+x离开,会提示是否保存,按y确定即可。
离开后,
crontab -l 查看是否已写入命令。
这个方法的神奇之处在于,你甚至可以设置执行该命令的user。
如下文我使用qq来执行,也可以用root之类的。
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
59 23 * * * qq /home/qq/anaconda3/bin/python /home/qq/test.py
然后使用: wq! 保存退出。
备注:网上有人说,方法1和方法2保存之后,都需要service cron restart。
亲测不必如此。
方法1 crontab -e之后,系统自动 "crontab: installing new crontab",显然不必再重启了。
方法2 vim /etc/crontab 之后,经过测试也会自动检查,到时间就运行。
如果像我这样,用【文件主】用户去执行,只需要chmod +x test.py ;
如果要用其他用户,自行查看linux下的文件权限管理。
最简单无脑的就是权限全开,chmod 777 test.py
若不设置权限,可能会无法运行。
然而crontab这个东西无法运行的时候不会报错也不会提醒,所以还是开一下权限的好。
如果你的.py文件使用了相对路径'./output/'之类的,可能会奇怪,为什么找不到输出。
我们进行一下测试,在test.py里放这么一段。
curpath=os.getcwd()
with open('/home/qq/out.txt','w') as f:
f.write(curpath)
实验结果表明:
1. 使用crontab -e 方法来设置的命令,当前是哪个用户,work_path就是哪个用户的根目录。
cwd = '/home/qq/'
所以设置out_path='./output/',会被拼成'/home/qq/output/'。
2.用vim /etc/crontab 方法来设置的命令,指定哪个用户,work_path就是哪个用户的根目录。
如果指定qq,则cwd='/home/qq/';
如果指定root,则cwd='/root/';
做好上面的工作之后仍然可能执行无效。
我们平时可以直接执行 python test.py,是因为已经在/etc/profile等地方设置好了环境变量。
对python进行了link,系统知道python在哪。
然而crontab使用的是自己的环境变量配置文件,自己搞一套,不服从大部队。
所以有解决方案:
1.使用可执行文件的绝对路径
该方法对crontab -e 和 vim /etc/crontab 两种方式都有效。
59 23 * * * /home/qq/anaconda3/bin/python /home/qq/test.py
这里我写入了anaconda里面的python绝对路径。
想用虚拟环境,也可以参照此法自行修改。
2.设置crontab的环境变量
先执行:
vim /etc/crontab
我们可以看到文件最上方有设置PATH的地方
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
很简单,在PATH这行,后面加个路径就可以了。
比如说改成:
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/home/qq/anaconda3/bin/
别问太长了怎么办,我也不知道怎么换行......
个人推荐方法1,灵活调换。不同的python环境改个路径就可以了。
//感谢https://www.cnblogs.com/cuisi/p/6251848.html