我有2个py。文件:
1。我有4个工人。每个工人工作10秒。程序的总执行时间为10秒。所以所有工人同时工作。
import asyncio
from time import sleep, time
from concurrent.futures import ProcessPoolExecutor
num_jobs = 4
queue = asyncio.Queue()
executor = ProcessPoolExecutor(max_workers=num_jobs)
loop = asyncio.get_event_loop()
def work():
sleep(10)
async def producer():
tasks = [loop.run_in_executor(executor, work) for _ in range(num_jobs)]
for f in asyncio.as_completed(tasks, loop=loop):
results = await f
await queue.put(results)
async def consumer():
completed = 0
while completed < num_jobs:
job = await queue.get()
completed += 1
if __name__ == '__main__':
s = time()
loop.run_until_complete(asyncio.gather(producer(), consumer()))
print("duration", time() - s)
2。Python Telegram Bot,它使用Webhooks来接收来自用户的消息。这个bot在10秒后接收来自用户和的消息发送回显信息给用户。但这不是第一种情况下的结果。在第二种情况下,消息不会同时处理。
import asyncio
import logging
from aiogram.dispatcher import Dispatcher
from aiogram.utils.executor import start_webhook
from aiogram import Bot, types
from bot_files.config import *
bot = Bot(token=bot_token)
dp = Dispatcher(bot)
# webhook settings
WEBHOOK_HOST = f'https://2568-176-8-60-184.ngrok.io'
WEBHOOK_PATH = f'/webhook/{bot_token}'
WEBHOOK_URL = f'{WEBHOOK_HOST}{WEBHOOK_PATH}'
# webserver settings
WEBAPP_HOST = '0.0.0.0'
WEBAPP_PORT = os.getenv('PORT', default=5000)
async def on_startup(dispatcher):
await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=True)
async def on_shutdown(dispatcher):
await bot.delete_webhook()
@dp.message_handler()
async def echo(message: types.Message):
await asyncio.sleep(10)
await message.answer(message.text)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
start_webhook(
dispatcher=dp,
webhook_path=WEBHOOK_PATH,
skip_updates=True,
on_startup=on_startup,
on_shutdown=on_shutdown,
host=WEBAPP_HOST,
port=WEBAPP_PORT,
)
我想把@dp.message_handler()
放在loop.run_until_complete(asyncio.gather(producer()))
中,这样一个producer()
。但我不能把decorator作为参数。我的问题是:如何在Python上同时处理来自多个用户的消息,比如第一种情况?我知道怎么进行长时间的投票。有可能为Webhooks做吗??
如果你的机器人在Webhooks上工作,Aiogram有一个特殊的装饰器,用于同时处理来自许多用户的消息- async_task
: https://docs.aiogram.dev/en/latest/_modules/aiogram/dispatcher/dispatcher.html#Dispatcher.async_task。