Python3 实现程序运行状态的监听

# -*- coding:utf-8 -*-

import threading
import psutil
import os
import time
'''
通过 threading.Thread.is_active 判断线程是否退出。
此方法可以用来对程序进行监听,当程序出现异常退出,重启程序。

'''


class MyThread(threading.Thread):

    def __init__(self, threadID, name, func, param=None):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.func = func
        self.param = param


    def run(self):
        lock = threading.Lock()
        if lock.acquire():  # 加锁
            if self.param is None:
                self.func()  # 调用传进来的函数
            else:
                self.func(self.param)
            print(self.name, time.ctime)
            lock.release()  # 释放锁


def test_func():
    i = 0
    while i < 60:
        i += 1
        print('i : {}'.format(str(i)))
        time.sleep(1)


def check_threading(t1):
    '''
    检测t1 线程是否退出
    :param t1:
    :return:
    '''
    while True:
        print(threading.Thread.is_alive(t1))
        if not threading.Thread.is_alive(t1):  # 如果线程退出, 重新创建一个进程
            t1 = MyThread(1, 'test_func', test_func)
            t1.start()
            t1.join()
        time.sleep(60)


thread_list = []
t1 = MyThread(1, 'test_func', test_func)
thread_list.append(t1)
thread_list.append(MyThread(2, 'check_threading', check_threading, t1))
for t in thread_list:
    t.start()
for t in thread_list:
    t.join()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值