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)
posted @ 2020-12-09 15:01  rm-rf*  阅读(77)  评论(0编辑  收藏  举报