当前位置: 首页 > news >正文

python 写一个监控另一个 程序中方法超时与否的服务

# monitor_service.pyimport logging
from logging.handlers import TimedRotatingFileHandler
from flask import Flask, jsonify,request
import threading
import time
import os
# 创建一个TimedRotatingFileHandler对象,每天更换一次日志文件
log_handler = TimedRotatingFileHandler('monitor_service.log', when='midnight', interval=1, backupCount=7)
log_handler.suffix = "%Y-%m-%d"  # 设置文件后缀为年-月-日
log_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))# 将handler添加到root logger
logging.getLogger().addHandler(log_handler)
logging.getLogger().setLevel(logging.INFO)
app = Flask(__name__)# 存储被监控进程的字典,格式为 {进程ID: 最后成功时间戳}
monitored_processes = {}
# 设置超时时间(秒)
TIMEOUT = 3@app.route('/register', methods=['POST'])
def register_process():data = request.jsonprocess_id = data['process_id']monitored_processes[process_id] = time.time()return jsonify({'status': 'success', 'message': 'Process registered successfully.'})@app.route('/success', methods=['POST'])
def process_success():data = request.jsonprocess_id = data['process_id']timestamp = data['timestamp']monitored_processes[process_id] = timestampreturn jsonify({'status': 'success', 'message': 'Process success reported.'})def monitor():while True:current_time = time.time()for process_id in list(monitored_processes):if current_time - monitored_processes[process_id] > TIMEOUT:kill_process(process_id)monitored_processes.pop(process_id, None)  # 从监控列表中移除time.sleep(1)  # 检查间隔时间def kill_process(process_id):try:os.kill(process_id, -9)  # 发送SIGKILL信号杀死进程logging.info(f"Process {process_id} has been killed due to timeout.")except OSError as e:logging.error(f"Error killing process {process_id}: {e}")# 启动监控线程
monitor_thread = threading.Thread(target=monitor)
monitor_thread.daemon = True
monitor_thread.start()if __name__ == '__main__':app.run(debug=True)
import requests
import time
import osdef monitored_method():# Here is the method that is being monitoredprint("执行被监控的方法")time.sleep(11)  # Simulating the execution time of the methodreturn Truedef register_process(process_id):# Register the process with the monitoring servicetry:response = requests.post('http://127.0.0.1:5000/register', json={'process_id': process_id})response.raise_for_status()  # Raises an HTTPError for bad responsesexcept requests.RequestException as e:print(f"Failed to register process: {e}")def report_success(process_id):# Report the successful execution to the monitoring servicetry:response = requests.post('http://127.0.0.1:5000/success', json={'process_id': process_id, 'timestamp': time.time()})response.raise_for_status()except requests.RequestException as e:print(f"Failed to report success: {e}")def report_failure(process_id, error):# Report the failure to the monitoring servicetry:response = requests.post('http://127.0.0.1:5000/failure', json={'process_id': process_id, 'error': str(error), 'timestamp': time.time()})response.raise_for_status()except requests.RequestException as e:print(f"Failed to report failure: {e}")if __name__ == '__main__':process_id = os.getpid()while True:try:register_process(process_id)if monitored_method():report_success(process_id)else:report_failure(process_id, "monitored_method returned False")except Exception as e:print(f"An error occurred: {e}")report_failure(process_id, e)# Wait for a specified interval before the next executiontime.sleep(10)

http://www.mrgr.cn/news/52475.html

相关文章:

  • ShuffleNet通道混合轻量级网络的深入介绍和实战
  • 纯干货!一文搞懂自动化测试哪些事儿!
  • vue npm run ...时 报错-系统找不到指定的路径
  • 网络爬虫中的几种数据存储方式(上篇)
  • 删除链表的倒数第 n 个结点,删除排序链表中的重复元素 II
  • 【工具变量】上市公司企业广告支出数据(2007-2023年)
  • 基于SSM电子资源管理系统的设计
  • Java常用API
  • 电脑桌面便签怎么添加,好用便签软件怎么样?
  • D40【python 接口自动化学习】- python基础之函数
  • 天文备忘录
  • Java之集合介绍
  • java HashMap源码剖析
  • GESP CCF python四级编程等级考试认证真题 2024年9月
  • 【数据结构】宜宾大学-计院-实验三
  • GitHub如何推送文件到仓库?
  • RHCE——笔记
  • 解读 Java 经典巨著《Effective Java》90条编程法则,第4条:通过私有构造器强化不可实例化的能力
  • 【R语言】gadm全球行政区划数据库
  • 线性可分支持向量机的原理推导 线性分隔超平面关于任意样本点 (x_i,y_i)的几何间隔 公式解析