经常我们会发现服务器跑着跑着内存使用率达到了百分之八九十,或者有时候直接挂掉,在我们还没定位是哪块代码有问题导致内存占用很大的时候,可以先写个定时脚本,当服务器内存使用率达到一定值的时候,就重启一起服务,释放内存。下面这个定时脚本是每隔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)

#   os.system(cmd)

#    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)

相关文章: