以服务的形式接收在钉钉中和机器人对话的消息. 如果我创建了多个机器人, 我在代码中该如何启动多个服务来接收消息?
我有如下代码:
def client(app_key, app_secret):
credential = dingtalk_stream.Credential(app_key, app_secret)
client = dingtalk_stream.DingTalkStreamClient(credential)
client.register_all_event_handler(MyEventHandler())
client.register_callback_handler(dingtalk_stream.ChatbotMessage.TOPIC, MyCallbackHandler())
client.start_forever()
如果我想创建多个client并且同时运行, 我该怎么做?
现在是我使用多线程创建多个client,代码如下:
def main():
threads = []
thread1 = threading.Thread(target=client, args=(
"xxx", "xxx"))
thread2 = threading.Thread(target=client, args=(
"xxx", "xxx"))
threads.append(thread1)
threads.append(thread2)
for thread in threads:
thread.start()
报错:RuntimeError: cannot schedule new futures after interpreter shutdown
多线程 问题
避免使用全局解释器锁(GIL):
如果你的程序是 CPU 密集型的,使用多线程可能不是最佳选择,因为 Python 的 GIL 会限制多线程的并行执行。
使用线程池的示例代码:
import threading
from concurrent.futures import ThreadPoolExecutor
import time
def client(app_key, app_secret):
credential = dingtalk_stream.Credential(app_key, app_secret)
client = dingtalk_stream.DingTalkStreamClient(credential)
client.register_all_event_handler(MyEventHandler())
client.register_callback_handler(dingtalk_stream.ChatbotMessage.TOPIC, MyCallbackHandler())
client.start_forever()
def main():
with ThreadPoolExecutor(max_workers=2) as executor:
futures = [
executor.submit(client, "xxx", "xxx"),
executor.submit(client, "yyy", "yyy")
]
# 等待所有线程完成
for future in futures:
future.result()
if __name__ == "__main__":
main()
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。