参考的文章:https://www.oschina.net/question/172446_2159505
先简单粗暴的解决,以后再优化(暂时不考虑强制停止线程的安全性等问题)
thread_dict = {}
def check_ThreadDict():
for tid,starttime in thread_dict.items():
if time.time() - starttime >=60: #大于一分钟的就kill
stop_thread(tid)
def _async_raise(tid, content, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
print("stop thread " + str(tid))
def stop_thread(threadident, content):
_async_raise(threadident,content, SystemExit)
class MyTimer(threading.Thread): # 定时任务
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("定时任务已启动")
scheduler = BlockingScheduler()
scheduler.add_job(check_ThreadDict, 'interval', seconds=60)
scheduler.start()
class TestThread(threading.Thread):
def run(self):
print("begin")
thread_dict[self.ident] = time.time()
while True:
time.sleep(0.1)
print("end")
if __name__ == '__main__':
time_start=time.time()
MyTimer().start()
while True:
time_end = time.time()
if time_end -time_start <= 3600:
cpu_used = psutil.cpu_percent(interval=1)
memory_used = psutil.virtual_memory().percent
""" 注"""
if memory_used < 90 and cpu_used < 95:
# print("cpu和内存使用率", cpu_used, memory_used)
pass
else:
time.sleep(3)
continue
t = TestThread()
t.start()
continue
break

536





