【Linux】crontab 定時任務 遇到幾個問題

cron 與 crontab 區別

cron 是提供定時任務的服務
crontab 是在cron服務下具體每一條任務,可以理解爲 cron table

bash xxx.sh 可以執行,但是crontab定時任務不執行,也沒有報錯信息,無日誌;

* * * * * /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1

首先區分 crontab -e 和 /etc/crontab

  • 使用命令 crontab -e 然後直接編輯定時腳本。 時間 +具體的名字
  • 這樣執行以後,屬於用戶自定義的,會被寫到 /var/spool/cron 目錄下,生成一個和用戶名一致的文件,文件內容就是我們編輯的定時腳本。
  • (系統級的)做系統級配置我們會直接配置 /etc/crontab
  • (用戶級的)一般還是建議大家使用 crontab -e ,這樣系統也會幫着檢查我們配置的腳本語法。
  • 如果用戶級別定時任務(crontab -e)不能執行,可以嘗試 改爲 系統級別定時任務(/etc/crontab)

crond[1655]: (bash) ERROR (getpwnam() failed)

  • 場景:
    /etc/crontab中,寫入 * * * * * bash /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1,報錯crond[1655]: (bash) ERROR (getpwnam() failed)
  • 解決:
沒有寫用戶root導致
* * * * * /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1 錯誤寫法

# *  *  *  *  * user-name  command to be executed
* * * * * root /root/xxx.sh /root/xxx.conf 1>/dev/null 2>&1 正確的方式

定時任務輸出內容寫入 /var/spool/mail/root 文件

# 去掉末尾 2>&1
* * * * * root /root/xxx.sh /root/xxx.conf 1>/dev/null

日誌信息:Removed slice User Slice of root.

/var/log/messages 文件部分信息

systemd: Created slice User Slice of root.
systemd: Started Session 1529 of user root.
systemd: Removed slice User Slice of root.

解決

這些是與片的創建和刪除有關的消息,這些消息在systemd中用於對進程進行分組並管理其資源。
爲什麼默認情況下會記錄它們,這使我無所適從,但是我已經看到了兩種禁用它們的方法:
較少干擾的方法是通過創建具有以下內容的/etc/rsyslog.d/ignore-systemd-session-slice.conf來過濾掉它們:

if $programname == "systemd" and ($msg contains "Starting Session" or $msg contains "Started Session" or $msg contains "Created slice" or $msg contains "Starting user-" or $msg contains "Removed Slice" or $msg contains "Stopping user-") then stop

然後重新啓動rsyslogd systemctl restart rsyslog

更廣泛的方法是通過編輯將systemd日誌記錄級別設置得更高一些/etc/systemd/system.conf:

#LogLevel=info
LogLevel=notice

參考:
https://unix.stackexchange.com/questions/267965/system-log-full-of-session-and-slice-messages
https://access.redhat.com/solutions/1564823

crontab定時任務不執行注意點

  1. 腳本中涉及文件路徑時寫絕對路徑

  2. 腳本執行要用到環境變量時,通過source命令顯式引入,例如:

#!/bin/sh
source/etc/profile
  1. 當手動執行腳本沒問題,但是crontab不執行時,可以嘗試在crontab中直接引入環境變量解決問題,例如:
0 * * * * /etc/profile;/bin/sh/path/to/myscript.sh

參考鏈接:
https://zhang.ge/5093.html

docker container 使用crontab

見:https://muguang.me/it/2659.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章