永远不会引发asyncio.TimeoutError

时间:2016-10-26 15:08:18

标签: python python-3.4 python-asyncio

我想测试asyncio如何处理阻止进程。

我的代码肯定有问题,因为永远不会提出asyncio.TimeoutError

import asyncio, random, time

q = asyncio.Queue()

MAX_WAIT = 5

@asyncio.coroutine
def blocking_task(sec):
    print('This task will sleep {} sec.'.format(sec))
    time.sleep(sec)

@asyncio.coroutine
def produce():
    while True:
        q.put_nowait(random.randint(1,10))
        yield from asyncio.sleep(0.5 + random.random())

@asyncio.coroutine
def consume():
    while True:
        value = yield from q.get()
        try:
            yield from asyncio.wait_for(blocking_task(value), MAX_WAIT)
        except asyncio.TimeoutError:
            print('~/~ Job has been canceled !!')
        else:
            print('=/= Job has been done :]')


loop = asyncio.get_event_loop()
asyncio.ensure_future(produce())
asyncio.ensure_future(consume())
loop.run_forever()

此代码产生以下输出:

$ ./tst3.py 
This task will sleep 2 sec.
=/= Job has been done :]
This task will sleep 1 sec.
=/= Job has been done :]
This task will sleep 7 sec.
=/= Job has been done :]

1 个答案:

答案 0 :(得分:2)

  

使用asyncio.sleep代替sleep

TimeoutError of asynciobuildin TimeoutError不同。这就是为什么你不能使用time.sleep来触发这个错误。要在asyncio.coroutine中触发TimeoutError,您只能使用由asyncio模块实现的计时器。

@asyncio.coroutine
def blocking_task(sec):
    print('This task will sleep {} sec.'.format(sec))
    yield from asyncio.sleep(sec)

<强>结果

This task will sleep 10 sec.
~/~ Job has been canceled !!
This task will sleep 3 sec.
=/= Job has been done :]
This task will sleep 4 sec.
=/= Job has been done :]
This task will sleep 2 sec.
=/= Job has been done :]
This task will sleep 7 sec.
~/~ Job has been canceled !!
This task will sleep 2 sec.
=/= Job has been done :]