import threading
import time

class TaskManager:
def __init__(self):
self.should_stop = False
self.thread = None

def background_task(self):
"""后台任务,但支持优雅关闭"""
while not self.should_stop:
# 执行一次任务
print("执行任务...")
time.sleep(1)

# 清理资源
print("🔧 正在清理资源...")
time.sleep(0.5)
print("✅ 资源清理完成")

def start(self):
self.thread = threading.Thread(target=self.background_task, daemon=True)
self.thread.start()

def stop(self):
"""请求停止,但等待清理完成"""
self.should_stop = True
self.thread.join(timeout=2) # 最多等2秒清理

# 使用
manager = TaskManager()
manager.start()
time.sleep(3) # 运行3秒
manager.stop() # 优雅停止

posted on 2025-12-26 15:20  偷懒的阿贤  阅读(1)  评论(0)    收藏  举报