使用下面的代码,我尝试使用 asyncio 启动 2 个无限循环:async def do_job_1(): while True : print('do_job_1') await asyncio.sleep(5)async def do_job_2(): while True : print('do_job_2') await asyncio.sleep(5)if __name__ == '__main__': asyncio.run(do_job_1()) asyncio.run(do_job_2())do_job_1块do_job_2,因为do_job_2从不打印 do_job_1。我犯了什么错误?最终我试图转换kafka消费者代码:from confluent_kafka import Consumer, KafkaErrorsettings = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'mygroup', 'client.id': 'client-1', 'enable.auto.commit': True, 'session.timeout.ms': 6000, 'default.topic.config': {'auto.offset.reset': 'smallest'}}c = Consumer(settings)c.subscribe(['mytopic'])try: while True: msg = c.poll(0.1) if msg is None: continue elif not msg.error(): print('Received message: {0}'.format(msg.value())) elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}' .format(msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str()))except KeyboardInterrupt: passfinally: c.close()摘自https://www.confluence.io/blog/introduction-to-apache-kafka-for-python-programmers是并发的,这样我就可以并行处理 Kafka 消息。
1 回答
回首忆惘然
TA贡献1847条经验 获得超11个赞
来自help(asyncio.run):
它应该用作 asyncio 程序的主要入口点,并且最好只调用一次。
但您可以使用asyncio.gather加入任务:
import asyncio
async def do_job_1():
while True :
print('do_job_1')
await asyncio.sleep(5)
async def do_job_2():
while True :
print('do_job_2')
await asyncio.sleep(5)
async def main():
await asyncio.gather(do_job_1(), do_job_2())
if __name__ == '__main__':
asyncio.run(main())
添加回答
举报
0/150
提交
取消