Три способа выполнить множество задач с asyncio
Функция для примера:
async def do_it(n):
await asyncio.sleep(random.uniform(0.5, 1))
return n
1. Последовательный вызов
async def main():
for i in range(100):
result = await do_it(i)
Такой вызов имеет смысл только тогда, когда результат одной задачи требуется для вызова следующей.
Если они независимы, то это антипаттерн, так как аналогичен простому синхронному вызову по очереди.
2. Упорядоченный результат
async def main():
tasks = [do_it(i) for i in range(100)]
results = await asyncio.gather(*tasks)
Выполняет корутины конкурентно и возвращает результат в виде списка.
Полезен когда требуется получить результаты в том же порядке в котором задачи отправлены.
3. Результат по мере готовности
tasks = [asyncio.create_task(do_it(i)) for i in range(100)]
for cor in asyncio.as_completed(tasks):
result = await cor
Так же выполняет корутины конкурентно, но не гарантирует порядок. Результат возвращается по мере готовности, каждый отдельно.
Полезен когда нужно обработать любой ответ как можно скорее.
#async
#java#docker#mybatis#oss#springboot#vue
RuoYi-Vue-Plus is a free, open-source backend framework upgraded from RuoYi for distributed clusters and multi-tenant use, built with Spring Boot 3.5, Vue3, TypeScript, MyBatis-Plus, and Redisson. It offers superior features like plugin decoupling, advanced permissions, multi-database support, workflows, code generation, Docker deployment, monitoring, and data security tools—far beyond original RuoYi. You benefit by building scalable enterprise apps 80% faster with less code, easier maintenance, and robust security for production. Warning: Versions ≤5.5.3 have critical flaws (CVE-2025-66916 RCE, CVE-2026-2819 auth bypass); update immediately.
https://github.com/dromara/RuoYi-Vue-Plus
#SpringBoot#RESTAPI#BackendDevelopment#CodeWithMosh#Java#StripeIntegration#CloudDeployment#LearnToCode
🚀 Ready to take your backend skills to the next level?
🔗Spring Boot: Mastering REST API Development🎓
- Learn to build clean, secure RESTful APIs
- Add authentication, role-based access, and JWT security 🔒
- Integrate Stripe for real payment processing 💳
- Deploy your app and database to the cloud ☁️
- Apply industry best practices for production-ready code 🛠
👉 Join now @repo_science and start building real-world projects like a pro!
#javascript#approval_process#cms#crm#ehr#erp#hr#layui#mysql#oa#privileges#redis#skyeye#springboot#springboot2#springcloud_vue#websocket
This platform uses Springboot, Layui, UNI-APP, and Ant Design Vue to create a low-code system for intelligent manufacturing. It includes over 30 application modules and more than 50 electronic workflows, covering CRM, ERP, MES, and more. This system streamlines business processes from customer relations to production and after-sales service, improving efficiency and data transparency. It also manages employee operations, providing a comprehensive solution for businesses. The benefits include faster development, reduced redundancy, and enhanced data management, making it ideal for companies seeking digital transformation.
https://github.com/dromara/skyeye