歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux自動關機及計算任務管理腳本

Linux自動關機及計算任務管理腳本

日期:2017/2/28 16:27:44   编辑: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


在執行完後所有該做循環這後,也可以加上關機的命令。

提供一個思路,可以干的其它事就靠自己的想象力了。

Copyright © Linux教程網 All Rights Reserved