import asyncio
@asyncio.coroutine
def task(dur):
print("task start")
yield from asyncio.sleep(dur) # time-consuming task
print("task finished")
return "result of the %s task" % ['long','short'][dur%2]
def main():
print("starting a long task")
x = asyncio.async(task(4)) # start the task
yield from asyncio.sleep(0.5) # do something else
print("half a sec later")
yield from asyncio.sleep(1) # do something else again
print("a sec more")
result = yield from x # now we need to use the result
print("yielded result: %s" % result)
yield from asyncio.sleep(1)
# But what if the task is short?
print("starting a short task")
x = asyncio.async(task(1)) # start the task
yield from asyncio.sleep(0.5) # do something else
print("half a sec later")
yield from asyncio.sleep(1) # do something else again
print("a sec more")
result = yield from x # now we need to use the result
print("yielded result: %s" % result)
yield from asyncio.sleep(1)
print("finished")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())