In the following example, I expect that f1() and f2() can stop after 2s. However, I can run f1() in 3s.
import asyncio
import time
async def f1():
print("start sleep")
time.sleep(3) # simulate CPU intensive part
print("end sleep")
print("start asyncio.sleep")
await asyncio.sleep(3) # simulate IO intensive part
print("end asyncio.sleep")
async def f2():
print("start asyncio.sleep")
await asyncio.sleep(3) # simulate IO intensive part
print("end asyncio.sleep")
print("start sleep")
time.sleep(3) # simulate CPU intensive part
print("end sleep")
async def main():
print("-----f1-----")
t1 = time.time()
try:
await asyncio.wait_for(f1(), timeout=2)
except:
pass
t2 = time.time()
print(f"f1 cost {(t2 - t1)} s")
print("-----f2-----")
t1 = time.time()
try:
await asyncio.wait_for(f2(), timeout=2)
except:
pass
t2 = time.time()
print(f"f2 cost {(t2 - t1)} s")
if __name__ == '__main__':
asyncio.run(main())
the result:
-----f1-----
start sleep
end sleep
start asyncio.sleep
f1 cost 3.0005991458892822 s
-----f2-----
start asyncio.sleep
f2 cost 2.0014591217041016 s
In my practical usecase, f1() has two parts, the first part is CPU intensive and the second part is I/O intensive(only for the 2nd part, I use async syntax). I hope the whole f1() can stop after fixed time. How to implement this usecase?