我有一个用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库中
你知道一些替代方法来避免工作流阻塞在执行给定的代码,以避免不良用户体验与电报机器人?谢谢你
我找到了答案。我只是将代码的阻塞部分封装在另一个函数中,并使用线程来创建并行线程。这样,主线程就不会阻塞,bot仍能正常工作:
相关问题 更多 >
编程相关推荐