python协程需要注意的
python协程需要注意的点
都在注释里
# -*- coding: utf-8 -*-
import asyncio
import time
from geeker import schedule
async def first():
await asyncio.sleep(1)
return "result first"
async def second():
await asyncio.sleep(1)
return "result second"
# 发送请求
async def get_data(y):
await first()
await second()
print(f'{y}号任务完成')
def callback(*args,**kwargs):
print('callback')
def run():
print('in run...')
# 如果在线程中执行任务,则必须使用这种方式创建loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# semaphore必须在loop创建之后再创建
semaphore = asyncio.Semaphore(40)
# 协程任务
tasks = {get_data(1), get_data(2), get_data(3), get_data(4)}
tasks = asyncio.wait(tasks, loop=loop)
loop.run_until_complete(tasks)
loop.close()
print("over")
if __name__ == '__main__':
schedule.every(3).seconds.do(run)
while True:
schedule.run_pending()
time.sleep(1)
你要是觉得写的还不错,就点个关注,可以评论区留下足迹,以后方便查看.
你要是觉得写的很辣鸡,评论区欢迎来对线!
欢迎转载!