python定時腳本判斷服務器內存

常常咱們會發現服務器跑着跑着內存使用率達到了百分之八九十,或者有時候直接掛掉,在咱們還沒定位是哪塊代碼有問題致使內存佔用很大的時候,能夠先寫個定時腳本,當服務器內存使用率達到必定值的時候,就重啓一塊兒服務,釋放內存。下面這個定時腳本是每隔10s去判斷一下機器的內存,假如內存使用率超過10%,就重啓一下進程(正常狀況下內存使用率是%5左右,因此就定了個10%),代碼以下面藍色部分所示。而後修改腳本權限,用於命令讓它在後頭不掛斷運行:nohup python -u restart.py >nohup.out 2>&1 &
python

#! /usr/bin/env python
# -*- coding:utf-8 -*-服務器

import os
import time
import datetime
import sched
import datetime
import psutilspa

#schedule_time = sched.scheduler(time.time,time.sleep)rest

schedule = sched.scheduler(time.time,time.sleep)orm

#def perform_command_time(cmd,inc):
#   schedule_time.enter(inc,0,perform_command_time,(cmd,inc))
#   os.system(cmd)
dns

def perform_command(cmd,inc):
    schedule.enter(inc,0,perform_command,(cmd,inc))
    memory = psutil.virtual_memory()
    percent = memory.percent
    if percent < 10:
        now = datetime.datetime.now()
        print now
        print percent
    if percent >=10:
        now = datetime.datetime.now()
        print now
        print percent
        os.system('ps -ef | grep supervisord | grep -v grep | cut -c 9-15 | xargs kill -9')
        os.system('ps -ef | grep ncq.dnsquery_monitor0_check | grep -v grep | cut -c 9-15 | xargs kill -9')
        time.sleep(5)
        os.system('supervisord -c /opt/trunk/conf.d/supervisord.conf')
        os.system('supervisorctl -uxxx -pxxx restart all')
        time.sleep(5)
#def timming_exe(cmd,inc=60):
#    schedule_time.enter(inc,0,perform_command_time,(cmd,inc))
#    schedule_time.run()
進程

def restart_exe(cmd,inc=5):
    schedule.enter(inc,0,perform_command,(cmd,inc))
    schedule.run()內存

#print("show date after 10 seconds:")
#timming_exe('date',10)
print("restart celery----------->")
restart_exe('supervisorctl -uxxx -pxxx restart all',10)
#restart_exe('df -h',12)utf-8

相關文章
相關標籤/搜索