测试线程发送。防止阻塞
This commit is contained in:
@@ -10,11 +10,35 @@ contacts_bp = Blueprint('contacts', __name__, url_prefix='/contacts')
|
|||||||
def send_message_in_thread(func, *args, **kwargs):
|
def send_message_in_thread(func, *args, **kwargs):
|
||||||
"""在独立线程中发送消息"""
|
"""在独立线程中发送消息"""
|
||||||
def run():
|
def run():
|
||||||
|
loop = None
|
||||||
try:
|
try:
|
||||||
# 在新线程中运行异步函数
|
# 创建新的事件循环
|
||||||
asyncio.run(func(*args, **kwargs))
|
loop = asyncio.new_event_loop()
|
||||||
|
asyncio.set_event_loop(loop)
|
||||||
|
|
||||||
|
# 运行异步函数
|
||||||
|
loop.run_until_complete(func(*args, **kwargs))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"发送消息失败: {e}")
|
logger.error(f"发送消息失败: {e}")
|
||||||
|
finally:
|
||||||
|
# 确保清理资源
|
||||||
|
if loop is not None:
|
||||||
|
try:
|
||||||
|
# 取消所有待处理的任务
|
||||||
|
pending = asyncio.all_tasks(loop)
|
||||||
|
for task in pending:
|
||||||
|
task.cancel()
|
||||||
|
|
||||||
|
# 运行事件循环直到所有任务都被取消
|
||||||
|
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
|
||||||
|
|
||||||
|
# 停止事件循环
|
||||||
|
loop.stop()
|
||||||
|
|
||||||
|
# 关闭事件循环
|
||||||
|
loop.close()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"清理资源失败: {e}")
|
||||||
|
|
||||||
# 创建并启动线程
|
# 创建并启动线程
|
||||||
thread = threading.Thread(target=run)
|
thread = threading.Thread(target=run)
|
||||||
|
|||||||
Reference in New Issue
Block a user