具有功能同步阻塞的电报bot问题

2024-09-30 02:16:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用python编写的telegrambot,允许用户在AWS中创建EC2实例。代码如下:

# We create the new EC2 instance for the new user
instance_id, ec2 = generateInstanceForUser(user_id)

i = ec2.Instance(id=instance_id) # instance id
i.start()
i.wait_until_running()
i.load()
time.sleep(45)

# Create account in DB
createAccountDB(user_id, username, user.mail, instance_id)

# Now that the instance and the account have been created, now settings have to be updated too
updateSettings(user_id, dictChange)

问题是函数generateInstanceForUser(user_id)阻塞了工作流,以及以下5行(很明显,使用time.sleep()函数)。最后一个函数updateSettings()通过SSH连接到刚刚创建的机器并执行一些操作。在不考虑延迟的情况下,这个工作流工作得很好

但是,由于我使用的是电报机器人,在这部分代码中,机器人会在2分钟内冻结。因此,如果有其他用户发送命令,bot不会响应,这显然是不可取的

注意:使用的函数保存在boto3库中

问题

你知道一些替代方法来避免工作流阻塞在执行给定的代码,以避免不良用户体验与电报机器人?谢谢你


Tags: theinstance函数代码用户idnewtime
1条回答
网友
1楼 · 发布于 2024-09-30 02:16:19

我找到了答案。我只是将代码的阻塞部分封装在另一个函数中,并使用线程来创建并行线程。这样,主线程就不会阻塞,bot仍能正常工作:

threads = []
t = threading.Thread(target=workerFunc, args=(apiKey, apiSecret, user_id, startStepValue, username, user, bot, update, leverageValue))
threads.append(t)
t.start()

相关问题 更多 >

    热门问题