原文鏈接:https://vien.tech/article/157
前言
本文將介紹ubuntu系統(tǒng)下如何定時執(zhí)行shell腳本、python腳本,ubuntu系統(tǒng)有一個定時任務(wù)的管理器crontab,我們只需要編輯定時任務(wù),然后重啟定時任務(wù)服務(wù)就好了。
crontab
編輯定時任務(wù)
參數(shù)定義:
- -u 指定用戶, - -l 列出用戶任務(wù)計劃,
- -r 刪除用戶任務(wù),
- -e 編輯用戶任務(wù)
英文介紹:
# 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 每個小時的第幾分鐘執(zhí)行該任務(wù)
- h 每天的第幾個小時執(zhí)行該任務(wù)
- dom 每月的第幾天執(zhí)行該任務(wù)
- mon 每年的第幾個月執(zhí)行該任務(wù)
- dow 每周的第幾天執(zhí)行該任務(wù) - command 指定要執(zhí)行的程序
分 小時 日 月 星期 命令
0-59 0-23 1-31 1-12 0-6 command
其他:
- 其中星期中0表示周日。
- * 代表任何時間,比如第一個分鐘,用 * 就代表每一小時的每一分鐘都執(zhí)行
- - 表示區(qū)間,比如1-3
- , 如果區(qū)間不連續(xù),可以用,例如1,3,6 編輯完成后wq 保存退出
重啟服務(wù)
注意事項
注意,一定要用絕對路徑。否則可能會執(zhí)行失敗。
比如,我們要執(zhí)行
那么你需要干的第一件事是
以此來查看python命令的真正路徑
root@ubuntu:~# which python
/root/.pyenv/shims/python
然后,查看bwh.py的全路徑,在bwh.py所在文件夾下
然后路徑便為
所以整條記錄應(yīng)該這樣編輯
0 9 * * * /root/.pyenv/shims/python /app/python/blog/bwh.py > /tmp/new_blog_bwh.log
上面的記錄是指每天9點整執(zhí)行/root/.pyenv/shims/python /app/python/blog/bwh.py
并將打印日志輸出到/tmp/new_blog_bwh.log
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。