Centos7的crontab定時任務和錯誤解決
阿新 • • 發佈:2018-12-14
保證已經安裝crontab
yum install crontabs
crontab基本指令
crontab -l # 列出定時任務列表
crontab -e # 編輯定時任務
新增需要定時執行的指令碼
# test1.sh
#!/bin/bash
source /etc/profile
function test1()
{
echo "hello world!";
}
test1
# test2.sh
#!/bin/bash
source /etc/profile
echo "start...";
echo $PWD
source /home/test_shell/test1.sh >> /home/test_shell/log &
echo "end...";
crontab -e
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
*/1 * * * * ./home/test_shell/test2.sh # 定時指令
啟動
systemctl restart crond.service # 重啟定時任務, 只有restart和reload兩個命令
service cornd status # 檢視執行報錯情況
檢視執行和監控
tail -f /var/log/cron # 執行日誌檢視看
tail -f /var/spool/mail/root # 執行結果日誌
報錯
tail -f /var/log/cron # 執行日誌查,發現
# 出錯位置
1288 Oct 11 14:13:01 iz2zeglob57mds4wy3xxfbz CROND[22676]: (root) CMD (123 >> /home/test_shell/test2.sh)
1289 Oct 11 14:13:01 iz2zeglob57mds4wy3xxfbz CROND[22675]: (root) MAIL (mailed 32 bytes of output but got status 0x004b#01 2)
解決:
檢視是否是路徑問題
*/1 * * * * ./home/test_shell/test2.sh # 需要放在sh指令碼的絕對路徑
檢視crontab執行轉態
service cornd status
# 報錯
send-mail: fatal: parameter inet_interfaces: no local interface found for ::1
crontab執行會發送郵件,修改postfix的配置檔案 (116行位置)
# The inet_interfaces parameter specifies the network interface
# addresses that this mail system receives mail on. By default,
# the software claims all active interfaces on the machine. The
# parameter also controls delivery of mail to [email protected][ip.address].
#
# See also the proxy_interfaces parameter, for network addresses that
# are forwarded to us via a proxy or network address translator.
#
# Note: you need to stop/start Postfix when this parameter changes.
#
#inet_interfaces = all
#inet_interfaces = $myhostname
#inet_interfaces = $myhostname, localhost
inet_interfaces = localhost
# Enable IPv4, and IPv6 if supported
inet_protocols = all
改為:
inet_interfaces = all
inet_protocols = all
重啟:
service postfix start 或者
systemctl start postfix.service
最後
在重啟crontab,檢視 /var/spool/mail/root中的結果
From [email protected] Thu Oct 11 16:30:01 2018
Return-Path: <[email protected]>
X-Original-To: root
Delivered-To: [email protected]
Received: by iz2zeglob57mds4wy3xxfbz.localdomain (Postfix, from userid 0)
id 43F7540FD4; Thu, 11 Oct 2018 16:30:01 +0800 (CST)
From: "(Cron Daemon)" <[email protected]>
To: [email protected]
Subject: Cron <[email protected]> ./home/test_shell/test2.sh
Content-Type: text/plain; charset=UTF-8
Auto-Submitted: auto-generated
Precedence: bulk
X-Cron-Env: <XDG_SESSION_ID=1090>
X-Cron-Env: <XDG_RUNTIME_DIR=/run/user/0>
X-Cron-Env: <LANG=en_US.UTF-8>
X-Cron-Env: <SHELL=/bin/bash>
X-Cron-Env: <PATH=/sbin:/bin:/usr/sbin:/usr/bin>
X-Cron-Env: <MAILTO=root>
X-Cron-Env: <HOME=/>
X-Cron-Env: <LOGNAME=root>
X-Cron-Env: <USER=root>
Message-Id: <[email protected]>
Date: Thu, 11 Oct 2018 16:30:01 +0800 (CST)
start...
/
end...
這樣就應該可以了!