我有一个用python编写的电报机器人,可以让用户在亚马逊网络服务中创建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)问题是function generateInstanceForUser(user_id)阻塞了工作流,以及以下5行(很明显,使用time.sleep() function)。最后一个函数updateSettings()通过SSH连接到刚刚创建的机器并执行一些操作。在不考虑延迟的情况下,此工作流运行良好。
但是,由于我使用的是Telegram机器人,在代码的这一部分,机器人在2分钟内冻结。因此,如果有其他用户发送命令,机器人就不会响应,这显然是不可取的。
注意:使用的函数保存在boto3库中。
问题
您是否知道在执行给定代码期间避免工作流阻塞的替代方法,以避免Telegram bot的不良用户体验?谢谢。
发布于 2019-03-01 02:30:18
我给自己找到了答案。我只是将代码的阻塞部分封装在另一个函数中,并使用线程来创建并行线程。这样,主线程将不会阻塞,机器人仍将继续正常工作:
threads = []
t = threading.Thread(target=workerFunc, args=(apiKey, apiSecret, user_id, startStepValue, username, user, bot, update, leverageValue))
threads.append(t)
t.start()https://stackoverflow.com/questions/54931184
复制相似问题