python管理易报错代码-易错任务线程监控

在这里插入代码片
import os
import time


# tv2.py 是一个需要一直运行的任务线程。
#任务线程每执行一次都往os.path.join('config', 'check.txt')该路径下
#写下当前时间戳,即任务进程的心跳


# 进程杀死程序,防止进程假死影想进程重新启动

def kill_progress(pname):
    # 查询py程序的运行进程id
    run_status = os.popen('pgrep -a python|grep {}'.format(pname))
    pid = run_status.read().split(' ')[0]
    # 使用kill杀死进程
    cmd = os.system('kill {}'.format(pid))

def run():
    #判断时间间隔(单位秒)
    sleep_time_thr = 60
  

    try:
	# 读取check.txt文件(任务进程的心跳)
        with open(os.path.join('config', 'check.txt'), 'r') as timet:
            # 任务进程最近一次的心跳时间
            last_time = timet.read()
        #当前时间
        current_time = time.time()
        #如果last_time 时间比较新,说明任务线程一直活着,否则就挂了,需要重新启动。
        if current_time - float(last_time) < sleep_time_thr:
            print('It is running, please wait')
            time.sleep(10)
        else:
            #读取主任物的线程id,并杀死。因为这个时候有可能是假死,所以要先杀死,再重新启动
            run_status = os.popen('pgrep -a python|grep tv2.py')
            pid = run_status.read().split(' ')[0]
            cmd = os.system('kill {}'.format(pid))
            #启动任务线程
            s = os.system('nohup python tv2.py & > nohupout1.out &')
            print('rerun..')
            time.sleep(10)

      
    except:
        print('RUN error1')
       

if __name__ == "__main__":
    """
    Examples:
        run
    """
    while True:
        run()
        print('waiting for new data')
        for i in range(10):
            print('waiting for new data {} '.format(i))
            time.sleep(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值