话不多说直接上代码,希望帮助到需要的人
# coding=utf-8
import time
import asyncio
import aiohttp
from threading import Thread
# 目标协程
async def run():
print("start get:")
print(time.time())
res = await get()
print("finish get:")
print(time.time())
# 异步请求
async def get():
url = 'http://www.baidu.com'
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
# return await response.read()
return await asyncio.sleep(2) # 假设请求返回时间
async def create_task(event_loop):
while True:
asyncio.run_coroutine_threadsafe(run(), event_loop)
await asyncio.sleep(1) # 设置定时时间
# 启动一个loop
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
if __name__ == '__main__':
thread_loop = asyncio.new_event_loop() # 子线程loop
run_loop_thread = Thread(target=start_loop, args=(thread_loop,))
run_loop_thread.start()
main_loop = asyncio.new_event_loop()
main_loop.run_until_complete(create_task(thread_loop)) # 在主线程loop里面执行子线程loop
结果
start get:
1574594992.7886512
start get:
1574594993.7891903
start get:
1574594994.7893755
finish get:
1574594994.885034
start get:
1574594995.7895672
finish get:
1574594995.8094516
start get:
1574594996.7900815
finish get:
1574594996.8099844
start get:
1574594997.7906814
finish get:
1574594997.8126216
结果解释:
每隔1秒就发起请求,不会等finish再发起
2秒后第一个请求回应,接着每隔1s会解决完一个请求
定时异步请求完成