cd /usr/local
vim cleanCacheTime.sh
把以下代码粘贴进去
#!/bin/bash echo "start SyncCleanCache.sh..." >> /var/log/mem_detect.log #系统分配的区总量 mem_total=`free -m | awk 'NR==2' | awk '{print $2}'` #当前剩余的大小 mem_free=`free -m | awk 'NR==3' | awk '{print $4}'` #当前已使用的used大小 mem_used=`free -m | grep Mem | awk '{print $3}'` echo "已使用:" >> /var/log/mem_detect.log echo $mem_used >> /var/log/mem_detect.log if (($mem_used != 0)); then #如果已被使用,则计算当前剩余free所占总量的百分比,用小数来表示,要在小数点前面补一个整数位0 mem_per=0`echo "scale=2;$mem_free/$mem_total" | bc` DATA="$(date -d "today" +"%Y-%m-%d-%H-%M") free percent is : $mem_per" echo $DATA >> /var/log/mem_detect.log #设置的告警值为20%(即使用超过80%的时候告警)。 mem_warn=0.20 #当前剩余百分比与告警值进行比较(当大于告警值(即剩余20%以上)时会返回1,小于(即剩余不足20%)时会返回0 ) mem_now=`expr $mem_per > $mem_warn` echo "是否大于告警值:" >> /var/log/mem_detect.log echo $mem_now >> /var/log/mem_detect.log #如果当前使用超过80%(即剩余小于20%,上面的返回值等于0),释放内存 if (($mem_now == 0)); then echo "more than percent 80..." >> /var/log/mem_detect.log #重启tomcat并清空缓存 pid=`ps aux | grep tomcat | grep -v grep | grep -v retomcat | awk '{print $2}'` echo $pid if [ -n "$pid" ] then { echo ===========shutdown================ /usr/local/apache-tomcat-7.0.65/bin/shutdown.sh sleep 1 pid=`ps aux | grep tomcat | grep -v grep | grep -v retomcat | awk '{print $2}'` sync echo 1 > /proc/sys/vm/drop_caches echo 2 > /proc/sys/vm/drop_caches echo 3 > /proc/sys/vm/drop_caches if [ -n "$pid" ] then { sleep 1 echo ========kill tomcat============== kill -9 $pid sync echo 1 > /proc/sys/vm/drop_caches echo 2 > /proc/sys/vm/drop_caches echo 3 > /proc/sys/vm/drop_caches } fi sleep 2 echo ===========startup.sh============== /usr/local/apache-tomcat-7.0.65/bin/startup.sh } else echo ===========startup.sh============== /usr/local/apache-tomcat-7.0.65/bin/startup.sh fi sync echo 1 > /proc/sys/vm/drop_caches echo 2 > /proc/sys/vm/drop_caches echo 3 > /proc/sys/vm/drop_caches #将release memory OK !写入temp文件夹的memstat_日期.log日志中 echo "--->release memory OK ! " >> /var/log/mem_detect.log fi fi
授权
chmod 777 cleanCacheTime.sh
测试
./cleanCacheTime.sh
到日志文件中看是否有问题,若没有问题
crond -e
把下面这句粘贴进去并保存退出(每分钟执行一次)
*/1 * * * * /usr/local/cleanCacheTask.sh >>/usr/local/cleanCache.log
service crond start
结束