![crontab 無法透過工作腳本啟動服務](https://rvso.com/image/617260/crontab%20%E7%84%A1%E6%B3%95%E9%80%8F%E9%81%8E%E5%B7%A5%E4%BD%9C%E8%85%B3%E6%9C%AC%E5%95%9F%E5%8B%95%E6%9C%8D%E5%8B%99.png)
我的腳本在單獨運行時有效,但不能透過 crontab 運行
定時任務
[root@someserver:/]# crontab -l
SHELL=/bin/bash
PATH=/usr/lib64/qt-3.3/bin:/home/ec2/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
*/1 * * * * /bin/bash /opt/scripts/check_beaver_status.sh
有問題的腳本
#!/bin/bash
function check_if_beaver_running () {
current_script=`basename $0`
process_name="beaver"
/bin/ps aux | /bin/grep "${process_name}" | /bin/grep -v 'grep' | /bin/grep -v "$current_script"
if [ $? -eq 0 ]; then
echo "${process_name} running"
else
echo "${process_name}: not running, starting..."
if [ -f /var/run/logstash_beaver.pid ] ; then
/bin/rm -f /var/run/logstash_beaver.pid
fi
/sbin/service beaver start
fi
}
check_if_beaver_running
答案1
克朗德沒有跑步。
[root@someserver:]# service crond status
crond is stopped
[root@someserver:]# service crond start
[root@someserver:]# chkconfig crond on
我還將我的腳本更改為:
#!/bin/bash
# when running in crontab:
# SHELL=/bin/bash
# PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# */10 * * * * /bin/bash beaver_ensure_running.sh
START=false
readarray -t PIDS < <(exec pgrep -x beaver)
function stop_beaver {
/usr/sbin/service beaver stop
sleep 5s ## Optionally wait for processes to stop.
kill -s SIGTERM "${PIDS[@]}" ## Perhaps force another signal to them if it doesn't work with defuncts.
sleep 5s ## Optionally wait for processes to stop.
kill -s SIGKILL "${PIDS[@]}" ## Perhaps force another signal to them if it doesn't work with defuncts.
START=true
}
if [[ ${#PIDS[@]} -eq 0 ]]; then
echo "No beaver process was found."
START=true
elif [[ ${#PIDS[@]} -eq 1 ]]; then
echo "Processes found: ${PIDS[*]}"
echo "Only one beaver process found."
stop_beaver
elif ps -fp "${PIDS[@]}" | fgrep -F '<defunct>' >/dev/null; then
echo "Processes found: ${PIDS[*]}"
echo "Defunct beaver process found."
stop_beaver
else
echo "Processes found: ${PIDS[*]}"
fi
[[ $START == true ]] && /usr/sbin/service beaver start
答案2
我對這個問題的答案很感興趣,所以讓我幫你診斷一下。
嘗試將 cron 更改為:
*/1 * * * * /bin/bash -x /opt/scripts/check_beaver_status.sh > /tmp/crondiag.log 2>&1
也添加命令:
env
到腳本的頂部和腳本中函數呼叫的底部。
讓它運行一次並與我們分享結果。也許在 Pastie.org 之類的地方。