• python定时脚本判断服务器内存


    经常我们会发现服务器跑着跑着内存使用率达到了百分之八九十,或者有时候直接挂掉,在我们还没定位是哪块代码有问题导致内存占用很大的时候,可以先写个定时脚本,当服务器内存使用率达到一定值的时候,就重启一起服务,释放内存。下面这个定时脚本是每隔10s去判断一下机器的内存,假如内存使用率超过10%,就重启一下进程(正常情况下内存使用率是%5左右,所以就定了个10%),代码如下面蓝色部分所示。然后修改脚本权限,用于命令让它在后头不挂断运行:nohup python -u restart.py >nohup.out 2>&1 &

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

    import os
    import time
    import datetime
    import sched
    import datetime
    import psutil

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

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

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

    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)

  • 相关阅读:
    光庭杯第九题
    NYOJ 95
    NYOJ 31
    NYOJ 26
    HDOJ 1016(DFS)
    memset和memcpy和memcpy
    周期串
    C# BackgroudWorker
    Microsoft® SQL Server® 2008 Express以及Microsoft® SQL Server® 2008 R2 SP1下载地址
    事件(Event)
  • 原文地址:https://www.cnblogs.com/forward-wang/p/9152156.html
Copyright © 2020-2023  润新知