# Async function with timeout
Rather than implementing asynchronous timeout behavior manually, prefer [[built-in]] timeout functionality, such as `asyncio.timeout`, `trio.fail_after`, or `anyio.move_on_after`, among others.
```python
# Don't
async def long_running_task(timeout): ...
async def main():
await long_running_task(timeout=2)
# Do
async def long_running_task(): ...
async def main():
async with asyncio.timeout(2):
await long_running_task()
```
## Automation
This [[Anti-Patterns of Python|anti-pattern]] can be detected by [[Ruff]][^1] or the [[ASYNC - flake8-async]] extension:
List of rules that can be automated:
| Name | Code | Detected pattern |
| --------------------------------- | -------- | ---------------------------------------- |
| `async-function-with-timeout`[^2] | ASYNC109 | `await long_running_task(timeout=2)`<br> |
---
Bibliography:
- [Some thoughts on asynchronous API design in a post-async/await world - vorpus.org](https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#timeouts-and-cancellation)
---
[^1]: [flake8-async (ASYNC) - docs.astral.sh](https://docs.astral.sh/ruff/rules/#flake8-async-async)
[^2]: [async-function-with-timeout (ASYNC109) - docs.astral.sh](https://docs.astral.sh/ruff/rules/async-function-with-timeout/)