This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import datetime | |
import random | |
async def display_date(num, loop): | |
end_time = loop.time() + 50.0 | |
while True: | |
print("Loop: {} Time: {}".format(num, datetime.datetime.now())) | |
if (loop.time() + 1.0) >= end_time: | |
break | |
await asyncio.sleep(random.randint(0, 5)) | |
loop = asyncio.get_event_loop() | |
asyncio.ensure_future(display_date(1, loop)) | |
asyncio.ensure_future(display_date(2, loop)) | |
loop.run_forever() | |
############################# | |
import asyncio | |
import requests | |
async def main(): | |
loop = asyncio.get_event_loop() | |
future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com') | |
future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk') | |
response1 = await future1 | |
response2 = await future2 | |
print(response1.text) | |
print(response2.text) | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) | |
############################# | |
import asyncio | |
@asyncio.coroutine | |
def slow_operation(future): | |
yield from asyncio.sleep(1) | |
future.set_result('Future is done!') | |
loop = asyncio.get_event_loop() | |
future = asyncio.Future() | |
asyncio.ensure_future(slow_operation(future)) | |
loop.run_until_complete(future) | |
print(future.result()) | |
loop.close() | |
############################# | |
import asyncio | |
@asyncio.coroutine | |
def factorial(name, number): | |
f = 1 | |
for i in range(2, number+1): | |
print("Task %s: Compute factorial(%s)..." % (name, i)) | |
yield from asyncio.sleep(1) | |
f *= i | |
print("Task %s: factorial(%s) = %s" % (name, number, f)) | |
loop = asyncio.get_event_loop() | |
tasks = [ | |
asyncio.ensure_future(factorial("A", 2)), | |
asyncio.ensure_future(factorial("B", 3)), | |
asyncio.ensure_future(factorial("C", 4))] | |
loop.run_until_complete(asyncio.wait(tasks)) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment