Skip to content

Instantly share code, notes, and snippets.

@ayushgoel
Last active September 3, 2015 07:33
Show Gist options
  • Save ayushgoel/4d1278c3283642c43efd to your computer and use it in GitHub Desktop.
Save ayushgoel/4d1278c3283642c43efd to your computer and use it in GitHub Desktop.
Example using asyncio of Python 3
# def xx(num):
# n = 0
# while n < num:
# yield n
# print(n)
# n += 1
# x = xx(12)
# for i in x:
# print("asd", i)
import asyncio
import datetime
def main1():
@asyncio.coroutine
def hello_world():
print("hello_world")
yield from asyncio.sleep(0.1)
@asyncio.coroutine
def display_date(loop):
end_time = loop.time() + 1.0
while True:
print(datetime.datetime.now(), loop.time(), end_time)
if loop.time() >= end_time:
break
yield from asyncio.wait_for(hello_world(), 1.0)
loop = asyncio.get_event_loop()
loop.run_until_complete(display_date(loop))
loop.close()
def main2():
@asyncio.coroutine
def slow_op(future, loop):
yield from asyncio.sleep(1)
future.set_result('Done with slow_op')
print("Completed slow_op")
loop.stop()
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.async(slow_op(future, loop))
print("Should print before slow_op")
loop.run_forever()
loop.close()
if __name__ == '__main__':
main2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment