Linux腳本分享:自動關機與計算任務管理
編者按:本文分享的bash shell腳本用于實現Linux的自動關機,以及簡單的計算任務管理。可以延伸實現其他功能,這里主要是提供一個實現思路。
1.自動關機腳本
每隔一定時間檢測一次,如果不存在某個進程就關機,如果存在就休眠。
用法: ./腳本名 進程名 休眠時間
注意:要有關機的權限(一般來說是root用戶或者有sudoer權限)!
建議用法: screen ./腳本名 進程名 休眠時間
#/bin/bash
while :
do
thread_num=`ps -e |grep $1 | wc -l`
if [ $thread_num -eq 0 ]; then
date >> shutdowntime.log
shutdown -h
exit
else
echo "Sleeping $2 second..."
sleep $2
fi
done
2.計算任務管理腳本
簡單的計算任務管理:檢測某個為某個名字的進程的個數,如果不是少于設定的個數,就提交任務,直到進程數和設定的相等;如果進程數大于等于設定個數,就休眠一定時間。
用法:./腳本名 程序名 任務數 循環次數
建議用screen運行。
#!/bin/bash
pro_name=$1
task_num=$2
cycle_num=$3
i=1
while (( $i <= $cycle_num ))
do
pro_num=$(ps -A | grep $pro_name |wc -l)
if (( $pro_num < $task_num )); then
echo $i
#在這里寫要執行程序
sleep 1s
i=$(($i+1))
else
echo 'sleeping 600s'
sleep 600s
fi
done
另外,可以在循環中針對時段控制任務數:
core_num=`cat /proc/cpuinfo |grep 'core id' | wc -l`
time_hour=`date +%H`
if (( $time_hour >= 23 )) || (( $time_hour < 7 ); then
task_num=$core_num #晚上23:00以后到早上7點前這段時間,就按機器的core數來提任務
else
task_num=$(( $core_num / 2 )) #其它時間只占用一半的core數來用于任務
fi
在執行完后所有該做循環這后,也可以加上關機的命令。
原文:http://blog.sina.com.cn/s/blog_59cf67260100muoj.html
【編輯推薦】






















