crontab 定時執行python指令碼
阿新 • • 發佈:2019-02-18
參考網址:http://zhidao.baidu.com/question/145860117.html
<pre id="answer-content-440639755" class="answer-text mb-10" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 10px; background-color: rgb(255, 255, 255); padding: 0px; font-family: arial, 'courier new', courier, 宋體, monospace;"><span style="white-space: pre;"> </span> http://the5fire.com/ubuntu-crontab.html
首先是python程式,就不貼源程式了,把測試crontab的python程式寫出來吧。
crontest.py
- #!/usr/bin/python
- #encoding=utf-8
- import os
- outfileName = '/data5/outcid.txt'
- outfile = open(outfileName, 'w')
- outfile.write("This is crontab command test!")
- outfile.close()
crontab -e
輸入
*/2 * * * * python /data5/crontest.py >> /data5/crontest.py.log 2>&1
意思是每個兩分鐘就用python執行/data5目錄下的crontest.py,將日誌輸出值crontest.py.log中,當然,程式crongtest.py中的輸入到指定檔案的資料是不會輸入到該log檔案中的,後面那個2>&1的意思是把錯誤的輸出也輸出到標準輸出(2表示錯誤,2>表示錯誤輸出,&表示等同於,1表示正確),因此如果執行出錯也會把錯誤輸出到之前定義的log中。
以下為有用的參考資料:
<pre id="answer-content-440639755" class="answer-text mb-10" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 10px; padding: 0px; font-family: arial, 'courier new', courier, 宋體, monospace; background-color: rgb(255, 255, 255);"><span style="font-size: 18px;">分鐘 小時 日期 月份 周 命令 舉例: 每天8點30分執行命令/tmp/run.sh 30 8 * * * /tmp/run.sh 每兩小時執行命令/tmp/run.sh 0 */2 * * * /tmp/run.sh</span>
<span style="font-size: 18px;">設定的時候用crontab -e來設定 設定好後可以用crontab -l來檢視 設定好後不用重啟crontab服務,馬上生效 但至少間隔一分鐘,也就是說9:50分設定9:51分執行的命令,很可能是不會生效的,至少要設定9:52分執行。 你用哪個使用者執行crontab -e,那麼執行的時候就是以哪個使用者身份執行</span>
<span style="font-size: 18px;">以及這個網址 http://the5fire.com/ubuntu-crontab.html</span>