溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

ubuntu定時執(zhí)行python腳本怎么寫

發(fā)布時間:2022-10-21 11:09:13 來源:億速云 閱讀:149 作者:iii 欄目:服務器

本篇內(nèi)容主要講解“ubuntu定時執(zhí)行python腳本怎么寫”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“ubuntu定時執(zhí)行python腳本怎么寫”吧!

crontab

編輯定時任務

crontab -e

參數(shù)定義:

  • -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 每個小時的第幾分鐘執(zhí)行該任務

  • h 每天的第幾個小時執(zhí)行該任務

  • dom 每月的第幾天執(zhí)行該任務

  • mon 每年的第幾個月執(zhí)行該任務

  • dow 每周的第幾天執(zhí)行該任務 - command 指定要執(zhí)行的程序

分      小時    日      月       星期     命令
0-59   0-23   1-31   1-12     0-6     command

其他:

  • 其中星期中0表示周日。

  • * 代表任何時間,比如第一個分鐘,用 * 就代表每一小時的每一分鐘都執(zhí)行

  • - 表示區(qū)間,比如1-3

  • , 如果區(qū)間不連續(xù),可以用,例如1,3,6    編輯完成后wq 保存退出

重啟服務

service cron restart

注意事項

注意,一定要用絕對路徑。否則可能會執(zhí)行失敗。

比如,我們要執(zhí)行

python bwh.py

那么你需要干的第一件事是

which python

以此來查看python命令的真正路徑

root@ubuntu:~# which python
/root/.pyenv/shims/python

然后,查看bwh.py的全路徑,在bwh.py所在文件夾下

pwd
/app/python/blog

然后路徑便為

/app/python/blog/bwh.py

所以整條記錄應該這樣編輯

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

到此,相信大家對“ubuntu定時執(zhí)行python腳本怎么寫”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI