原文鏈接:https://vien.tech/article/157
前言
本文將介紹ubuntu系統下如何定時執行shell腳本、python腳本,ubuntu系統有一個定時任務的管理器crontab,我們只需要編輯定時任務,然后重啟定時任務服務就好了。
crontab
編輯定時任務
參數定義:
- -u 指定用戶, - -l 列出用戶任務計劃,
- -r 刪除用戶任務,
- -e 編輯用戶任務
英文介紹:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# 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/
中文解釋:
格式
m h dom mon dow command
以上為縮寫,這里提供全拼對照:
minute (m), hour (h), day of month (dom), month (mon), day of week (dow)
含義如下:
- m 每個小時的第幾分鐘執行該任務
- h 每天的第幾個小時執行該任務
- dom 每月的第幾天執行該任務
- mon 每年的第幾個月執行該任務
- dow 每周的第幾天執行該任務 - command 指定要執行的程序
分 小時 日 月 星期 命令
0-59 0-23 1-31 1-12 0-6 command
其他:
- 其中星期中0表示周日。
- * 代表任何時間,比如第一個分鐘,用 * 就代表每一小時的每一分鐘都執行
- - 表示區間,比如1-3
- , 如果區間不連續,可以用,例如1,3,6 編輯完成后wq 保存退出
重啟服務
注意事項
注意,一定要用絕對路徑。否則可能會執行失敗。
比如,我們要執行
那么你需要干的第一件事是
以此來查看python命令的真正路徑
root@ubuntu:~# which python
/root/.pyenv/shims/python
然后,查看bwh.py的全路徑,在bwh.py所在文件夾下
然后路徑便為
所以整條記錄應該這樣編輯
0 9 * * * /root/.pyenv/shims/python /app/python/blog/bwh.py > /tmp/new_blog_bwh.log
上面的記錄是指每天9點整執行/root/.pyenv/shims/python /app/python/blog/bwh.py
并將打印日志輸出到/tmp/new_blog_bwh.log
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。