CentOS 7定時執行python腳本
在CentOS下,可以使用crontab進行定時任務的處理,
一、crontab的安裝
默認情況下,CentOS 7中已經安裝有crontab,如果沒有安裝,可以通過yum進行安裝,
yum install crontabs
二、crontab的定時語法說明
corntab中,一行代碼就是一個定時任務,其語法結構可以通過這個圖來理解,

| 字符 | 含義 |
|---|---|
| * | 代表取值范圍內的所有 |
| / | 代表"每" |
| - | 代表從某個數字到某個數字 |
| , | 代表離散的取值(取值的串列) |
一些常用的時間寫法
| 運算式 | 含義 |
|---|---|
| * * * * * | 每分鐘執行 |
| * */4 * * * | 每4小時執行 |
| 0 4 * * * | 每天4點執行 |
| 0 12 */2 * * | 每2天執行一次,在12點0分開始運行 |
| * * * * 0 | 每周日執行 |
| * * * * 6,0 | 每周六、日執行 |
| 5 * * * * | 每小時的第5分鐘執行 |
三、設定定時任務
撰寫python腳本
# test.py
print("hello world!")
通過Finalshell上傳到指定目錄下

修改組態檔
[root@VM_0_8_centos script_py]# whereis crontab
crontab: /usr/bin/crontab /etc/crontab
[root@VM_0_8_centos script_py]# vim /etc/crontab
# 檔案末尾添加
* * * * * root /usr/bin/python3 /data/script_py/test.py > test.log
# 每分鐘 root身份執行 使用python3 運行 test.py 輸出到 test.log
重啟服務
systemctl restart crond
查看日志
[root@VM_0_8_centos script_py]# cat /root/test.log
hello world!
注意!
非常重要的一點是要用絕對路徑寫到命令,否則定時運行失敗,因此我們需要先弄清楚python的具體路徑,
# 查看系統默認安裝的python2的路徑
[root@VM_0_8_centos ~]# which python
/usr/bin/python
# 查看自行安裝的python3的路徑
[root@VM_0_8_centos ~]# which python3
/usr/bin/python3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/228400.html
標籤:Python
上一篇:爬小說
