> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/python/fastapi/fastapi-hou-tai-ren-wu.md).

# FastAPI 后台任务

我们在实际的开发中，都会遇到，我们要执行的一些任务很耗时，但是呢，对于前端呢，没必要进行等待。比如发送邮件，读取文件。我们在fastapi如何实现呢。

其实很简单，fastapi已经给我们封装好一个现成的模块，我们直接调用使用即可，非常方便。我们举一个简单例子演示下

```python
# coding: utf8

from fastapi import FastAPI, BackgroundTasks
import time


app = FastAPI()

def alter(email: str, msg = ""):
    time.sleep(5)
    print(email, msg)


@app.post('/send')
async def sendEmail(email: str, task: BackgroundTasks):
    task.add_task(alter, email, msg='不关注')
    return {"msg": '后台运行'}
# uvicorn main:app --reload --host 0.0.0.0
```
