Flask-SocketIO 中的后台任务

Background Tasks in Flask-SocketIO

我有一个非常直截了当的问题,但我还没有找到一个非常直截了当的答案:我什么时候应该使用 start_background_task() 而不是“正常”启动 Python 线程? Flask-SocketIO 文档指出:

This function returns an object compatible with the Thread class in the Python standard library. The start() method on this object is already called by this function.

关于是否有必要在每个 threading 模块初始化和启动线程时使用它并没有太多说明。

存在 start_background_task() 的原因是,根据您使用的 Web 服务器,线程模型会发生变化。例如,如果您使用的是 eventlet 或 gevent,则后台任务需要作为 greenlet 启动,而不是作为 Thread 实例。

如果您使用start_background_task(),您将保证使用与您的环境兼容的任务对象。