简体   繁体   中英

Cannot run a While Loop in AWS Python Lambda

import asyncio
from aiogram import Bot, Dispatcher, types

# Handlers
async def echo_hello(message: types.Message):
    while True:
        await message.reply("Hello!")
        await asyncio.sleep(20)
        
# AWS Lambda funcs
async def register_handlers(dp: Dispatcher):
    dp.register_message_handler(echo_hello, commands=['sayhello'])

async def process_event(event, dp: Dispatcher):
    Bot.set_current(dp.bot)
    update = types.Update.to_object(event)
    await dp.process_update(update)


async def main(event):
    bot = Bot(token=TOKEN)
    dp = Dispatcher(bot)

    await register_handlers(dp)
    await process_event(event, dp)

    return 'ok'


def lambda_handler(event, context):
    return asyncio.get_event_loop().run_until_complete(main(event))

I can't seem to get my telegram bot in AWS Python Lambda to loop the Hello message. Provided I got no idea how else to get the lambda_handler function, I only saw this as an example from https://github.com/DavisDmitry/aiogram-aws-serverless-example

EDIT: NVM the default timeout for functions is 15 minutes at best so any loop will only work for 15 minutes at the most.

As @luk2302 mentions in the comment above, indeed Lambdas only have an upper limit of at most 15 minutes customizable by the user in the settings.

If set to 15 minutes, any loop will execute for that amount of time given the conditions make it so. At the time I asked this question I was unaware of the fact and by default the timeout value was set to 5 seconds, while my code was putting the while loop to sleep for 20 seconds. Hence I was unable to get any repeated messages. Once I set it to 2 minutes (for example), it repeated the message about 6 times after which it stopped.

Lambda functions do run almost forever but these are not suitable for functions which might have long execution process (including loops). For that, EC2 instances can be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM