CentOS定时执行python脚本(crontabs)

配置crontabs

下载crontabs

yum install crontabs

PS:

# 查看有哪些定期执行的任务
crontab -l
# 编辑定期执行的任务(增删改)
crontab -e
# 启动
/bin/systemctl start crond.service
 
# 重启
/bin/systemctl restart crond.service
 
# 关闭
/bin/systemctl stop crond.service

# 查看crontab状态:
service crond status

.sh文件执行python文件

python文件(helloWorld.py)

# 把当前时间写入文件
import time
with open('/root/Weather/dateNow.txt','a') as f:
    f.write(str(time.time())+'\n')

.sh文件(helloWorld.sh)

编写.sh文件内容

source /etc/profile
source ~/.bash_profile
/usr/local/python/bin/python3 /root/Weather/helloWorld.py

文件路径如何获取
在这里插入图片描述
给.sh文件执行权限

chmod +x helloWorld.sh

执行.sh文件

./helloWorld.sh 

结果展示
在这里插入图片描述

定时执行.sh文件

打开执行任务列表

crontab -e

添加任务(一分钟触发一次,可参考下方更多内容)

* *1 * * *   /root/Weather/helloWorld.sh

在这里插入图片描述
重新启动

/bin/systemctl restart crond.service

结果展示:
在这里插入图片描述

PS:
在这里插入图片描述

*代表取值范围内的数字
/ 代表"每"
- 代表从某个数字到某个数字
, 代表离散的取值(取值的列表)

常用Demo
* * * * *     //每分钟执行
* */4 * * *   //每4小时执行
0 4 * * *     //每天4点执行
0 12 */2 * *  //每2天执行一次,在12点0分开始运行
* * * * 0     //每周日执行
* * * * 6,0   //每周六、日执行
5 * * * *     //每小时的第5分钟执行

猜你喜欢

转载自blog.csdn.net/Mr_Qian_Ives/article/details/107758878