溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Python檢測其他程序是否卡主了

發(fā)布時間:2020-08-02 10:05:40 來源:網(wǎng)絡(luò) 閱讀:431 作者:輝暉飛 欄目:編程語言

一、需求場景:

大量的windows上運行著某任務(wù)的Java程序,程序會出現(xiàn)莫名卡主。卡主時候系統(tǒng)資源利用率都正常,程序也只是卡主不會有任何錯誤提示,往往業(yè)務(wù)出現(xiàn)了問題再回頭去查時候才會發(fā)現(xiàn),不然就要派人定期巡檢。

二、想法:

觀察到程序卡主以后日志也停止輸出,可以定期對比日志和系統(tǒng)時間,超過規(guī)定的閥值視為異常,即刻重啟該程序(哎~有各種問題卻無人維護(hù)的程序還真不少,只能貼狗皮膏藥吧)

三、實踐:

# -*- coding: utf-8 -*-
import os
import time
import datetime
import subprocess
from dateutil.parser import parse


def error1(fun):
    def error2(doc):
        try:
            fun(doc)
        except Exception as reason:
            print(reason)
    return error2


def read_log(log_file):
    tag = -1
    flag = True
    with open(log_file, 'rb') as f:
        lines = f.readlines()
        while flag:
            try:
                last_line = str(lines[tag], encoding='gb2312')
                print('獲取到第%s行的數(shù)據(jù)為:\n%s' % (tag, last_line))
                log_time = last_line.split(",")[0]
                print('提取行數(shù)據(jù)中的時間為:%s' % (log_time))
                time_format = time.strptime(log_time, "%Y-%m-%d %H:%M:%S")
                print('時間格式正確!')
                flag = False
            except Exception as reason:
                print(reason)
                tag -= 1
        return log_time


def contrast_time(log_time):
    system_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print('獲取系統(tǒng)時間:%s' % (system_time))
    a = parse(log_time)
    b = parse(system_time)
    interval = (b - a).total_seconds()
    print("時間間隔為:%s秒" % (interval))
    return interval


def restart_script(interval, timeout, proc_name, cmd_file):
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    f = open('log.txt', 'a+')
    print('%s 執(zhí)行重啟' % (current_time), file=f)
    f.close()
    os.system('taskkill /IM %s /F' % (proc_name))
    os.system('taskkill /IM cmd.exe /F')
    time.sleep(1)
    subprocess.Popen("%s" % (cmd_file))


@error1
def main(intervals):
    print('檢查的文件為:%s' % (log_file))
    log_time = read_log(log_file)
    interval = contrast_time(log_time)
    if interval > timeout:
        print("檢測到超時,將重啟腳本....")
        restart_script(interval, timeout, proc_name, cmd_file)
    else:
        print("檢測到時間間隔在規(guī)定范圍內(nèi)")
    print('==============================================')
    time.sleep(intervals)


if __name__ == '__main__':
    intervals = 300
    timeout = 300
    proc_name = 'java.exe'
    log_file = 'C:\\mailboxcode\\log\\log_'
    cmd_file = 'C:\\check_log\\start_run.bat'
    while True:
        main(intervals)

    

四、運行演示:

如果最后一行數(shù)據(jù)不包含時間,將會繼續(xù)往上找一行。

使用Python檢測其他程序是否卡主了

使用Python檢測其他程序是否卡主了

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI