crontab使用
安装
yum install crontabs
查看服务状态
service crond status
开启
service crond start
加入开机服务中
chkconfig --level 35 crond on
查看crontab服务列表
(base) [root@localhost ~]# crontab -l
no crontab for root
说明现在没有定时任务。
编辑服务列表
crontab -e
这样会打开一个vim界面,编辑即可
08 14 * * * /home/software/anaconda3/bin/python3 /mnt/share/test.py
这个test.py我只写了一个打印“谢谢”到test.txt文件的函数,没有引用任何额外包。这是可以正常执行的。前面表示每天14:08分执行这个任务。
时间设定说明
(base) [root@localhost share]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# For details see man 4 crontabs
# Example of job definition:
# .---------------- 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
报错处理
python脚本不执行
我遇到的情况是,我用的是anaconda的一个环境,那么我要引入该环境的解释器,然后在我指定的路径下执行脚本。这样才会在指定时刻执行任务。
0 23 * * * export PATH=/这是python路径/bin/:$PATH;cd /脚本所在路径;python3 脚本名.py
修改通知邮件的收件人
crontab -e
添加
MAILTO=""
不要发送通知邮件
crond会将每次的输出信息(正常输出和报错)发给默认的收件人。在shell输入mail,可以看到类似这种
所以不想发的话可以修改任务:
crontab -e
0 23 * * * 命令 >/dev/null 2>&1